-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
918 lines (777 loc) · 35.7 KB
/
scanner.py
File metadata and controls
918 lines (777 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
#!/usr/bin/env python3
import os
import sys
import socket
import subprocess
import time
import ipaddress
import platform
import random
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime
import argparse
import signal
import threading
from threading import Lock
try:
import curses
from curses import textpad
except ImportError:
print("This script requires curses library. Install it with: pip install windows-curses (Windows) or use Linux/Termux")
sys.exit(1)
class AdvancedPingScanner:
def __init__(self):
self.lock = Lock()
self.scanning = False
self.stats = {
'total_scanned': 0,
'live_hosts': 0,
'start_time': None,
'end_time': None
}
def traditional_ping(self, ip, timeout=1, count=1, packet_size=56):
"""Traditional ICMP ping"""
try:
if os.name == 'nt': # Windows
cmd = f"ping -n {count} -w {timeout*1000} -l {packet_size} {ip}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0 and "TTL=" in result.stdout
else: # Linux/Android/Termux
cmd = f"ping -c {count} -W {timeout} -s {packet_size} {ip}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0 and "ttl=" in result.stdout.lower()
except Exception as e:
return False
def fast_ping(self, ip, timeout=2):
"""Fast ping using system command"""
try:
if os.name == 'nt': # Windows
response = os.system(f"ping -n 1 -w {timeout*1000} {ip} > NUL 2>&1")
else: # Linux/Android/Termux
response = os.system(f"ping -c 1 -W {timeout} {ip} > /dev/null 2>&1")
return response == 0
except:
return False
def tcp_ping(self, ip, port=80, timeout=2):
"""TCP ping (SYN scan)"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
result = s.connect_ex((ip, port))
return result == 0
except:
return False
def multi_tcp_ping(self, ip, ports=[80, 443, 22, 21, 23, 53, 8080], timeout=1):
"""Try multiple common ports"""
for port in ports:
if self.tcp_ping(ip, port, timeout):
return True, port
return False, None
def udp_ping(self, ip, port=53, timeout=2):
"""UDP ping for DNS"""
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(timeout)
if port == 53: # DNS
dns_query = b'\xaa\xaa\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x07version\x04bind\x00\x00\x10\x00\x03'
s.sendto(dns_query, (ip, port))
else:
s.sendto(b"ping", (ip, port))
try:
data, addr = s.recvfrom(1024)
return True
except socket.timeout:
return True
except:
return False
def arp_ping(self, ip, timeout=1):
"""ARP ping for local network"""
try:
if platform.system().lower() == 'windows':
cmd = f"arp -a {ip}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return ip in result.stdout and "dynamic" in result.stdout.lower()
else:
cmd = f"arping -c 1 -w {timeout} {ip} 2>/dev/null"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0
except:
return False
def get_hostname(self, ip):
"""Get hostname from IP"""
try:
return socket.gethostbyaddr(ip)[0]
except:
return "N/A"
def port_scan_fast(self, ip, ports=[21, 22, 23, 25, 53, 80, 110, 443, 993, 995, 8080, 8443], timeout=1):
"""Quick port scan"""
open_ports = []
for port in ports:
if self.tcp_ping(ip, port, timeout):
open_ports.append(port)
if len(open_ports) >= 3:
break
return open_ports
def service_detection(self, ip, port, timeout=1):
"""Basic service detection"""
service_map = {
21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS",
80: "HTTP", 110: "POP3", 443: "HTTPS", 993: "IMAPS", 995: "POP3S",
8080: "HTTP-ALT", 8443: "HTTPS-ALT"
}
return service_map.get(port, f"Port {port}")
def comprehensive_scan(self, ip, timeout=2, methods=None):
"""Comprehensive scan using multiple methods"""
if methods is None:
methods = ['icmp', 'tcp', 'udp', 'arp']
results = {
'ip': ip,
'alive': False,
'methods': {},
'hostname': 'N/A',
'open_ports': [],
'services': []
}
# Try different ping methods
if 'icmp' in methods:
results['methods']['icmp'] = self.fast_ping(ip, timeout)
# TCP checks
if 'tcp' in methods:
tcp_alive, tcp_port = self.multi_tcp_ping(ip, timeout=timeout)
results['methods']['tcp'] = tcp_alive
if tcp_alive and tcp_port:
results['methods']['tcp_port'] = tcp_port
# UDP checks
if 'udp' in methods:
results['methods']['udp_53'] = self.udp_ping(ip, 53, timeout)
# ARP check for local networks
if 'arp' in methods and self.is_local_ip(ip):
results['methods']['arp'] = self.arp_ping(ip, timeout)
# Determine if host is alive
alive_methods = [v for k, v in results['methods'].items() if v and k not in ['tcp_port']]
results['alive'] = any(alive_methods)
if results['alive']:
results['hostname'] = self.get_hostname(ip)
results['open_ports'] = self.port_scan_fast(ip, timeout=timeout)
for port in results['open_ports']:
service = self.service_detection(ip, port, timeout)
results['services'].append(f"{port}/{service}")
return results
def is_local_ip(self, ip):
"""Check if IP is in local network ranges"""
try:
ip_obj = ipaddress.ip_address(ip)
private_ranges = [
ipaddress.ip_network('10.0.0.0/8'),
ipaddress.ip_network('172.16.0.0/12'),
ipaddress.ip_network('192.168.0.0/16'),
]
return any(ip_obj in network for network in private_ranges)
except:
return False
class TermuxScannerGUI:
def __init__(self, stdscr):
self.stdscr = stdscr
self.scanner = AdvancedPingScanner()
self.current_menu = "main"
self.selected_option = 0
self.scan_results = []
self.input_buffer = ""
self.current_input_field = ""
self.scan_thread = None
# Telegram channel
self.telegram_channel = "https://t.me/Android_Ghosts"
# Configuration
self.config = {
'timeout': 2,
'threads': 20,
'methods': ['icmp', 'tcp', 'arp'],
'output_file': 'scan_results.txt',
'start_ip': '192.168.1.1',
'end_ip': '192.168.1.254',
'single_ip': '8.8.8.8',
'file_path': 'ips.txt'
}
self.setup_curses()
def setup_curses(self):
curses.start_color()
curses.use_default_colors()
# Define color pairs
curses.init_pair(1, curses.COLOR_GREEN, -1) # Green
curses.init_pair(2, curses.COLOR_RED, -1) # Red
curses.init_pair(3, curses.COLOR_YELLOW, -1) # Yellow
curses.init_pair(4, curses.COLOR_CYAN, -1) # Cyan
curses.init_pair(5, curses.COLOR_MAGENTA, -1) # Magenta
curses.init_pair(6, curses.COLOR_WHITE, -1) # White
curses.init_pair(7, curses.COLOR_BLUE, -1) # Blue
self.GREEN = curses.color_pair(1)
self.RED = curses.color_pair(2)
self.YELLOW = curses.color_pair(3)
self.CYAN = curses.color_pair(4)
self.MAGENTA = curses.color_pair(5)
self.WHITE = curses.color_pair(6)
self.BLUE = curses.color_pair(7)
def draw_header(self):
height, width = self.stdscr.getmaxyx()
# Clear screen
self.stdscr.clear()
# Draw header
header_text = "Android.Ghosts - Advanced Network Scanner"
version_text = "Termux Edition v2.0"
telegram_text = f"Telegram: {self.telegram_channel}"
self.stdscr.addstr(0, (width - len(header_text)) // 2, header_text, self.CYAN | curses.A_BOLD)
self.stdscr.addstr(1, (width - len(version_text)) // 2, version_text, self.YELLOW)
self.stdscr.addstr(2, (width - len(telegram_text)) // 2, telegram_text, self.MAGENTA | curses.A_BOLD)
# Draw separator
self.stdscr.addstr(3, 0, "=" * width, self.WHITE)
def draw_main_menu(self):
height, width = self.stdscr.getmaxyx()
menu_items = [
"🚀 Start Network Scan",
"⚙️ Configuration",
"📊 View Results",
"💾 Export Results",
"📱 Join Telegram Channel",
"❓ Help",
"🚪 Exit"
]
# Draw menu
self.stdscr.addstr(5, 2, "MAIN MENU:", self.MAGENTA | curses.A_BOLD)
for i, item in enumerate(menu_items):
if i == self.selected_option:
self.stdscr.addstr(7 + i, 4, f"> {item}", self.GREEN | curses.A_BOLD)
else:
self.stdscr.addstr(7 + i, 4, f" {item}", self.WHITE)
# Draw footer
footer = "Use ↑↓ to navigate, ENTER to select, q to quit"
self.stdscr.addstr(height - 2, (width - len(footer)) // 2, footer, self.YELLOW)
# Draw stats if available
if self.scanner.stats['total_scanned'] > 0:
stats = f"Last Scan: {self.scanner.stats['total_scanned']} hosts, {self.scanner.stats['live_hosts']} alive"
self.stdscr.addstr(height - 3, 2, stats, self.CYAN)
self.stdscr.refresh()
def draw_scan_menu(self):
height, width = self.stdscr.getmaxyx()
scan_options = [
"📡 Scan IP Range",
"🎯 Scan Single IP",
"📁 Scan from File",
"🔙 Back to Main Menu"
]
self.stdscr.addstr(5, 2, "SCAN OPTIONS:", self.MAGENTA | curses.A_BOLD)
for i, item in enumerate(scan_options):
if i == self.selected_option:
self.stdscr.addstr(7 + i, 4, f"> {item}", self.GREEN | curses.A_BOLD)
else:
self.stdscr.addstr(7 + i, 4, f" {item}", self.WHITE)
self.stdscr.refresh()
def draw_config_menu(self):
height, width = self.stdscr.getmaxyx()
config_items = [
f"Timeout: {self.config['timeout']}s",
f"Threads: {self.config['threads']}",
f"Methods: {', '.join(self.config['methods'])}",
f"Output File: {self.config['output_file']}",
f"Default Start IP: {self.config['start_ip']}",
f"Default End IP: {self.config['end_ip']}",
f"Default File: {self.config['file_path']}",
"🔙 Back to Main Menu"
]
self.stdscr.addstr(5, 2, "CONFIGURATION:", self.MAGENTA | curses.A_BOLD)
for i, item in enumerate(config_items):
if i == self.selected_option:
self.stdscr.addstr(7 + i, 4, f"> {item}", self.GREEN | curses.A_BOLD)
else:
self.stdscr.addstr(7 + i, 4, f" {item}", self.WHITE)
self.stdscr.refresh()
def draw_scan_progress(self, ip_list):
height, width = self.stdscr.getmaxyx()
self.stdscr.addstr(5, 2, "SCANNING IN PROGRESS...", self.YELLOW | curses.A_BOLD)
self.stdscr.addstr(6, 2, "Press 'q' to stop scan", self.RED)
# Progress bar area
progress_row = 8
self.stdscr.addstr(progress_row, 2, "Progress: [", self.WHITE)
# Results area
results_start = progress_row + 3
self.stdscr.addstr(results_start - 1, 2, "LIVE HOSTS:", self.GREEN | curses.A_BOLD)
return progress_row, results_start
def update_scan_progress(self, progress, live_hosts, current_ip, stats):
height, width = self.stdscr.getmaxyx()
# Clear previous content
for i in range(9, height - 3):
self.stdscr.addstr(i, 2, " " * (width - 4), self.WHITE)
# Update progress bar
progress_bar_width = 40
filled = int(progress_bar_width * progress / 100)
bar = "█" * filled + "░" * (progress_bar_width - filled)
self.stdscr.addstr(9, 2, f"{bar} {progress:.1f}%", self.CYAN)
# Update statistics
elapsed = datetime.now() - stats['start_time'] if stats['start_time'] else 0
rate = stats['total_scanned'] / elapsed.total_seconds() if elapsed.total_seconds() > 0 else 0
stats_text = f"Scanned: {stats['total_scanned']} | Live: {stats['live_hosts']} | Rate: {rate:.1f} hosts/s"
self.stdscr.addstr(10, 2, stats_text, self.WHITE)
self.stdscr.addstr(11, 2, f"Current: {current_ip}", self.YELLOW)
# Show live hosts (last 10)
start_row = 13
self.stdscr.addstr(start_row, 2, "Recent Live Hosts:", self.GREEN)
for i, (ip, info) in enumerate(live_hosts[-8:]):
services = ', '.join(info['services'][:2]) if info['services'] else 'No services'
host_info = f" {ip} ({info['hostname']}) - {services}"
if start_row + i + 1 < height - 2:
self.stdscr.addstr(start_row + i + 1, 2, host_info, self.GREEN)
self.stdscr.refresh()
def draw_results(self):
height, width = self.stdscr.getmaxyx()
self.stdscr.addstr(5, 2, f"SCAN RESULTS ({len(self.scan_results)} live hosts):", self.MAGENTA | curses.A_BOLD)
if not self.scan_results:
self.stdscr.addstr(7, 4, "No results available. Run a scan first.", self.YELLOW)
self.stdscr.addstr(9, 4, "Press any key to return...", self.WHITE)
self.stdscr.refresh()
self.stdscr.getch()
return
# Show results (scrollable)
start_row = 7
max_display = height - start_row - 3
for i, (ip, info) in enumerate(self.scan_results[:max_display]):
services = ', '.join(info['services'][:3]) if info['services'] else 'No services'
row_text = f"{ip:15} | {info['hostname'][:20]:20} | {services}"
self.stdscr.addstr(start_row + i, 2, row_text, self.GREEN)
if len(self.scan_results) > max_display:
self.stdscr.addstr(height - 2, 2, f"... and {len(self.scan_results) - max_display} more hosts", self.CYAN)
self.stdscr.addstr(height - 3, 2, "Press any key to return...", self.WHITE)
self.stdscr.refresh()
self.stdscr.getch()
def get_user_input(self, prompt, default=""):
height, width = self.stdscr.getmaxyx()
input_row = height - 3
# Clear input area
self.stdscr.addstr(input_row, 2, " " * (width - 4), self.WHITE)
self.stdscr.addstr(input_row, 2, f"{prompt}: {default}", self.CYAN)
self.stdscr.refresh()
input_buffer = default
cursor_pos = len(input_buffer)
while True:
# Show cursor
self.stdscr.addstr(input_row, 2 + len(prompt) + 2 + cursor_pos, "_", curses.A_BLINK)
self.stdscr.refresh()
key = self.stdscr.getch()
if key == curses.KEY_ENTER or key in [10, 13]:
break
elif key == curses.KEY_BACKSPACE or key == 127:
if cursor_pos > 0:
input_buffer = input_buffer[:cursor_pos-1] + input_buffer[cursor_pos:]
cursor_pos -= 1
elif key == 27: # ESC
return None
elif 32 <= key <= 126: # Printable characters
input_buffer = input_buffer[:cursor_pos] + chr(key) + input_buffer[cursor_pos:]
cursor_pos += 1
elif key == curses.KEY_LEFT and cursor_pos > 0:
cursor_pos -= 1
elif key == curses.KEY_RIGHT and cursor_pos < len(input_buffer):
cursor_pos += 1
# Update display
self.stdscr.addstr(input_row, 2, " " * (width - 4), self.WHITE)
self.stdscr.addstr(input_row, 2, f"{prompt}: {input_buffer}", self.CYAN)
return input_buffer
def read_ips_from_file(self, filename):
"""Read IPs from file with various formats support"""
try:
if not os.path.exists(filename):
return None, f"File not found: {filename}"
with open(filename, 'r', encoding='utf-8') as file:
ips = []
lines = file.readlines()
if not lines:
return None, "File is empty"
for line_num, line in enumerate(lines, 1):
line = line.strip()
if line and not line.startswith('#'):
# Support for CIDR notation
if '/' in line:
try:
network = ipaddress.ip_network(line, strict=False)
ips.extend([str(ip) for ip in network.hosts()])
except Exception as e:
# If CIDR fails, try as regular IP
try:
ipaddress.ip_address(line)
ips.append(line)
except:
pass
else:
# Regular IP or hostname
try:
# Try to validate as IP
ipaddress.ip_address(line)
ips.append(line)
except:
# Try DNS resolution for hostnames
try:
resolved_ip = socket.gethostbyname(line)
ips.append(resolved_ip)
except:
# If all fails, skip the line
pass
if not ips:
return None, "No valid IP addresses found in file"
return ips, f"Successfully loaded {len(ips)} IPs from {filename}"
except Exception as e:
return None, f"Error reading file: {str(e)}"
def run_scan(self, ip_list):
self.scanner.scanning = True
live_hosts = []
total = len(ip_list)
self.scanner.stats = {
'total_scanned': 0,
'live_hosts': 0,
'start_time': datetime.now(),
'end_time': None
}
try:
with ThreadPoolExecutor(max_workers=self.config['threads']) as executor:
future_to_ip = {
executor.submit(self.scanner.comprehensive_scan, ip, self.config['timeout'], self.config['methods']): ip
for ip in ip_list
}
for i, future in enumerate(as_completed(future_to_ip)):
if not self.scanner.scanning:
break
ip = future_to_ip[future]
try:
result = future.result()
if result['alive']:
live_hosts.append((ip, result))
# Update progress
progress = (i + 1) / total * 100
self.scanner.stats['total_scanned'] = i + 1
self.scanner.stats['live_hosts'] = len(live_hosts)
# Update display
self.update_scan_progress(progress, live_hosts, ip, self.scanner.stats)
except Exception as e:
pass
self.scan_results = live_hosts
self.save_results()
except Exception as e:
pass
finally:
self.scanner.scanning = False
def save_results(self):
try:
with open(self.config['output_file'], 'w', encoding='utf-8') as f:
f.write("Android.Ghosts Advanced Network Scanner - Results\n")
f.write(f"Telegram Channel: {self.telegram_channel}\n")
f.write(f"Scan Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Total Hosts Found: {len(self.scan_results)}\n")
f.write("=" * 80 + "\n\n")
for ip, info in self.scan_results:
f.write(f"IP: {ip}\n")
f.write(f"Hostname: {info.get('hostname', 'N/A')}\n")
f.write(f"Open Ports: {info.get('open_ports', [])}\n")
f.write(f"Services: {info.get('services', [])}\n")
f.write("-" * 40 + "\n")
except Exception as e:
pass
def generate_ip_range(self, start_ip, end_ip):
try:
start = ipaddress.ip_address(start_ip)
end = ipaddress.ip_address(end_ip)
if start > end:
start, end = end, start
ip_range = []
current = start
while current <= end:
ip_range.append(str(current))
current += 1
if len(ip_range) > 1000: # Safety limit
break
return ip_range
except Exception as e:
return []
def show_message(self, message, color=None):
"""Show a message to the user"""
height, width = self.stdscr.getmaxyx()
if color is None:
color = self.YELLOW
# Clear message area
self.stdscr.addstr(height - 4, 2, " " * (width - 4), self.WHITE)
self.stdscr.addstr(height - 4, 2, message, color)
self.stdscr.addstr(height - 3, 2, "Press any key to continue...", self.WHITE)
self.stdscr.refresh()
self.stdscr.getch()
def show_telegram_info(self):
"""Show Telegram channel information"""
height, width = self.stdscr.getmaxyx()
self.stdscr.clear()
self.draw_header()
telegram_info = [
"📱 Join Our Telegram Channel!",
"",
f"Channel: {self.telegram_channel}",
"",
"Why join?",
"• Get the latest updates",
"• Share your results",
"• Get help and support",
"• Learn advanced techniques",
"• Connect with other users",
"",
"Features you'll find:",
"• New scanning techniques",
"• Network security tips",
"• Tool updates and releases",
"• Community discussions",
"",
"Press any key to return..."
]
for i, line in enumerate(telegram_info):
if i + 5 < height:
if i == 0:
self.stdscr.addstr(5 + i, 2, line, self.MAGENTA | curses.A_BOLD)
elif "Channel:" in line:
self.stdscr.addstr(5 + i, 2, line, self.CYAN | curses.A_BOLD)
else:
self.stdscr.addstr(5 + i, 2, line, self.WHITE)
self.stdscr.refresh()
self.stdscr.getch()
def open_telegram_channel(self):
"""Try to open Telegram channel"""
try:
# For Termux, we can try to open the link
if os.name != 'nt': # Not Windows
os.system(f"termux-open-url '{self.telegram_channel}'")
self.show_message("Attempting to open Telegram...", self.GREEN)
else:
self.show_message(f"Please visit: {self.telegram_channel}", self.CYAN)
except:
self.show_message(f"Please visit: {self.telegram_channel}", self.CYAN)
def main_loop(self):
while True:
self.draw_header()
if self.current_menu == "main":
self.draw_main_menu()
elif self.current_menu == "scan":
self.draw_scan_menu()
elif self.current_menu == "config":
self.draw_config_menu()
key = self.stdscr.getch()
if key == curses.KEY_UP:
self.selected_option = max(0, self.selected_option - 1)
elif key == curses.KEY_DOWN:
if self.current_menu == "main":
self.selected_option = min(6, self.selected_option + 1)
elif self.current_menu == "scan":
self.selected_option = min(3, self.selected_option + 1)
elif self.current_menu == "config":
self.selected_option = min(7, self.selected_option + 1)
elif key == curses.KEY_ENTER or key in [10, 13]:
self.handle_menu_selection()
elif key == ord('q'):
if self.scanner.scanning:
self.scanner.scanning = False
else:
break
def handle_menu_selection(self):
if self.current_menu == "main":
if self.selected_option == 0: # Start Scan
self.current_menu = "scan"
self.selected_option = 0
elif self.selected_option == 1: # Configuration
self.current_menu = "config"
self.selected_option = 0
elif self.selected_option == 2: # View Results
self.draw_results()
elif self.selected_option == 3: # Export Results
if self.scan_results:
self.save_results()
self.show_message(f"Results exported to {self.config['output_file']}", self.GREEN)
else:
self.show_message("No results to export", self.RED)
elif self.selected_option == 4: # Join Telegram Channel
self.show_telegram_info()
self.open_telegram_channel()
elif self.selected_option == 5: # Help
self.show_help()
elif self.selected_option == 6: # Exit
raise KeyboardInterrupt
elif self.current_menu == "scan":
if self.selected_option == 0: # Scan IP Range
start_ip = self.get_user_input("Start IP", self.config['start_ip'])
if start_ip:
end_ip = self.get_user_input("End IP", self.config['end_ip'])
if end_ip:
ip_list = self.generate_ip_range(start_ip, end_ip)
if ip_list:
self.start_scan_display(ip_list)
else:
self.show_message("Invalid IP range", self.RED)
elif self.selected_option == 1: # Scan Single IP
single_ip = self.get_user_input("IP Address", self.config['single_ip'])
if single_ip:
# Validate IP
try:
ipaddress.ip_address(single_ip)
self.start_scan_display([single_ip])
except:
self.show_message("Invalid IP address", self.RED)
elif self.selected_option == 2: # Scan from File
file_path = self.get_user_input("File path", self.config['file_path'])
if file_path:
ip_list, message = self.read_ips_from_file(file_path)
if ip_list:
self.show_message(message, self.GREEN)
self.start_scan_display(ip_list)
else:
self.show_message(message, self.RED)
elif self.selected_option == 3: # Back
self.current_menu = "main"
self.selected_option = 0
elif self.current_menu == "config":
if self.selected_option == 0: # Timeout
new_timeout = self.get_user_input("Timeout (seconds)", str(self.config['timeout']))
if new_timeout and new_timeout.isdigit():
self.config['timeout'] = int(new_timeout)
elif self.selected_option == 1: # Threads
new_threads = self.get_user_input("Threads", str(self.config['threads']))
if new_threads and new_threads.isdigit():
self.config['threads'] = int(new_threads)
elif self.selected_option == 2: # Methods
self.configure_methods()
elif self.selected_option == 3: # Output File
new_output = self.get_user_input("Output file", self.config['output_file'])
if new_output:
self.config['output_file'] = new_output
elif self.selected_option == 4: # Start IP
new_start = self.get_user_input("Default Start IP", self.config['start_ip'])
if new_start:
self.config['start_ip'] = new_start
elif self.selected_option == 5: # End IP
new_end = self.get_user_input("Default End IP", self.config['end_ip'])
if new_end:
self.config['end_ip'] = new_end
elif self.selected_option == 6: # File Path
new_file = self.get_user_input("Default file path", self.config['file_path'])
if new_file:
self.config['file_path'] = new_file
elif self.selected_option == 7: # Back
self.current_menu = "main"
self.selected_option = 0
def configure_methods(self):
"""Configure scan methods"""
methods = ['icmp', 'tcp', 'udp', 'arp']
selected_methods = self.config['methods'].copy()
while True:
self.draw_header()
height, width = self.stdscr.getmaxyx()
self.stdscr.addstr(5, 2, "SELECT SCAN METHODS (SPACE to toggle, ENTER to confirm):", self.MAGENTA | curses.A_BOLD)
for i, method in enumerate(methods):
status = "✓" if method in selected_methods else "✗"
if i == self.selected_option:
self.stdscr.addstr(7 + i, 4, f"> [{status}] {method.upper()}", self.GREEN | curses.A_BOLD)
else:
self.stdscr.addstr(7 + i, 4, f" [{status}] {method.upper()}", self.WHITE)
self.stdscr.refresh()
key = self.stdscr.getch()
if key == curses.KEY_UP:
self.selected_option = max(0, self.selected_option - 1)
elif key == curses.KEY_DOWN:
self.selected_option = min(3, self.selected_option + 1)
elif key == ord(' '): # Space to toggle
method = methods[self.selected_option]
if method in selected_methods:
selected_methods.remove(method)
else:
selected_methods.append(method)
elif key == curses.KEY_ENTER or key in [10, 13]:
if selected_methods:
self.config['methods'] = selected_methods
break
elif key == 27: # ESC
break
def start_scan_display(self, ip_list):
height, width = self.stdscr.getmaxyx()
progress_row, results_start = self.draw_scan_progress(ip_list)
# Start scan in background thread
self.scan_thread = threading.Thread(target=self.run_scan, args=(ip_list,))
self.scan_thread.daemon = True
self.scan_thread.start()
# Wait for scan to complete or user interrupt
while self.scanner.scanning and self.scan_thread.is_alive():
time.sleep(0.1)
# Show completion message
if self.scanner.stats['total_scanned'] > 0:
self.show_message(f"Scan complete! Found {len(self.scan_results)} live hosts. Results saved to: {self.config['output_file']}", self.GREEN)
def show_help(self):
height, width = self.stdscr.getmaxyx()
help_text = [
"Android.Ghosts Network Scanner - Help",
"",
"Features:",
"• ICMP, TCP, UDP, and ARP scanning",
"• Multi-threaded for fast scanning",
"• Service detection on common ports",
"• Results export to file",
"• Support for IP ranges, single IP, and files",
"",
"File Format:",
"• One IP per line",
"• Support for CIDR notation (192.168.1.0/24)",
"• Support for hostnames",
"• Comments start with #",
"",
"Telegram Channel:",
f"• {self.telegram_channel}",
"• Get updates and support",
"• Share your results",
"",
"Navigation:",
"• Use UP/DOWN arrows to navigate",
"• ENTER to select options",
"• SPACE to toggle checkboxes",
"• q to quit",
"",
"Press any key to return..."
]
self.stdscr.clear()
self.draw_header()
for i, line in enumerate(help_text):
if i + 5 < height:
if i == 0:
self.stdscr.addstr(5 + i, 2, line, self.CYAN | curses.A_BOLD)
elif "Telegram Channel:" in line:
self.stdscr.addstr(5 + i, 2, line, self.MAGENTA | curses.A_BOLD)
elif self.telegram_channel in line:
self.stdscr.addstr(5 + i, 2, line, self.CYAN | curses.A_BOLD)
else:
self.stdscr.addstr(5 + i, 2, line, self.WHITE)
self.stdscr.refresh()
self.stdscr.getch()
def main(stdscr):
# Clear screen
stdscr.clear()
stdscr.refresh()
# Initialize GUI
gui = TermuxScannerGUI(stdscr)
try:
gui.main_loop()
except KeyboardInterrupt:
pass
except Exception as e:
stdscr.addstr(0, 0, f"Error: {e}", curses.A_BOLD)
stdscr.refresh()
stdscr.getch()
if __name__ == "__main__":
# Check if running in Termux
if not os.path.exists('/data/data/com.termux/files/usr'):
print("This script is optimized for Termux environment")
print("But can run on any system with Python and curses")
print("Android.Ghosts Advanced Network Scanner")
print("Telegram Channel: https://t.me/Android_Ghosts")
print("Starting...")
# Run the application
try:
curses.wrapper(main)
except KeyboardInterrupt:
print("\nScan interrupted by user")
except Exception as e:
print(f"Application error: {e}")