-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonScanner.py
More file actions
281 lines (239 loc) · 10.3 KB
/
Copy pathPythonScanner.py
File metadata and controls
281 lines (239 loc) · 10.3 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
#!/usr/bin/env python3
"""
Port Scanner - A lightweight, multi-threaded port scanning tool
Inspired by Nmap - Network Mapper
"""
import socket
import threading
import argparse
from datetime import datetime
import ipaddress
import time
import sys
import os
# Try to import colorama, use fallback if not available
try:
from colorama import init, Fore, Style
init(autoreset=True)
COLORAMA_AVAILABLE = True
except ImportError:
COLORAMA_AVAILABLE = False
# ANSI color codes for fallback
class Fore:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
RESET = '\033[0m'
class Style:
BRIGHT = '\033[1m'
DIM = '\033[2m'
NORMAL = '\033[22m'
RESET_ALL = '\033[0m'
class PortScanner:
def __init__(self):
self.open_ports = []
self.lock = threading.Lock()
self.total_ports = 0
self.scanned_ports = 0
self.start_time = None
def get_service_name(self, port):
"""Get service name for a port"""
services = {
20: "FTP-data", 21: "FTP", 22: "SSH", 23: "Telnet",
25: "SMTP", 53: "DNS", 80: "HTTP", 110: "POP3",
111: "RPCbind", 135: "MS RPC", 139: "NetBIOS",
143: "IMAP", 443: "HTTPS", 445: "SMB", 993: "IMAPS",
995: "POP3S", 1723: "PPTP", 3306: "MySQL",
3389: "RDP", 5432: "PostgreSQL", 5900: "VNC",
6379: "Redis", 8080: "HTTP-Alt", 27017: "MongoDB"
}
return services.get(port, "Unknown")
def get_banner(self, ip, port, timeout=2):
"""Get service banner from open port"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
sock.connect((ip, port))
# Send probe for banner grabbing
if port == 80 or port == 8080:
sock.send(b"HEAD / HTTP/1.0\r\n\r\n")
elif port == 443:
sock.send(b"HEAD / HTTP/1.0\r\n\r\n")
elif port == 22:
sock.send(b"SSH-2.0-Client\n")
elif port == 21:
sock.send(b"QUIT\n")
else:
sock.send(b"\n")
try:
banner = sock.recv(1024).decode('utf-8', errors='ignore')
banner = banner.replace('\n', ' ').replace('\r', ' ').strip()
if len(banner) > 80:
banner = banner[:80] + "..."
return banner if banner else "Banner unavailable"
except:
return "Banner unavailable"
finally:
sock.close()
except:
return "Banner unavailable"
def check_port(self, ip, port):
"""Check a single port"""
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
result = sock.connect_ex((ip, port))
with self.lock:
self.scanned_ports += 1
progress = (self.scanned_ports / self.total_ports) * 100
if result == 0:
service = self.get_service_name(port)
banner = self.get_banner(ip, port)
self.open_ports.append((port, service, banner))
# Show progress
bar = self.create_progress_bar(progress)
print(f"\r{Fore.GREEN}[+]{Style.RESET_ALL} Port {port}: {Fore.GREEN}OPEN{Style.RESET_ALL} ({service}) {bar} {progress:.1f}%", end="")
elif self.scanned_ports % 10 == 0:
bar = self.create_progress_bar(progress)
print(f"\r{Fore.YELLOW}[*]{Style.RESET_ALL} Scanning: {bar} {progress:.1f}%", end="")
sock.close()
except:
pass
def create_progress_bar(self, progress, length=30):
"""Create progress bar"""
filled = int(length * progress / 100)
bar = '█' * filled + '░' * (length - filled)
return f"[{bar}]"
def scan_port_range(self, ip, start_port, end_port, threads=50):
"""Scan a range of ports"""
if start_port < 1 or end_port > 65535 or start_port > end_port:
print(f"{Fore.RED}Error: Invalid port range (1-65535){Style.RESET_ALL}")
return
self.total_ports = end_port - start_port + 1
self.scanned_ports = 0
self.start_time = time.time()
print(f"{Fore.CYAN}{'='*70}")
print(f"{Fore.CYAN} PORT SCANNER v1.0{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*70}")
print(f"Target: {Fore.YELLOW}{ip}{Style.RESET_ALL}")
print(f"Port range: {Fore.YELLOW}{start_port}-{end_port}{Style.RESET_ALL}")
print(f"Threads: {Fore.YELLOW}{threads}{Style.RESET_ALL}")
print(f"Started: {Fore.YELLOW}{datetime.now().strftime('%H:%M:%S')}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*70}\n")
# Create and run threads
threads_list = []
for port in range(start_port, end_port + 1):
t = threading.Thread(target=self.check_port, args=(ip, port))
threads_list.append(t)
t.start()
if len(threads_list) >= threads:
for t in threads_list:
t.join()
threads_list = []
# Wait for remaining threads
for t in threads_list:
t.join()
self.display_results(ip)
def scan_common_ports(self, ip):
"""Scan common ports only"""
common_ports = [20, 21, 22, 23, 25, 53, 80, 110, 111, 135, 139, 143,
443, 445, 993, 995, 1723, 3306, 3389, 5432, 5900, 6379, 8080, 27017]
self.total_ports = len(common_ports)
self.scanned_ports = 0
self.start_time = time.time()
print(f"{Fore.CYAN}{'='*70}")
print(f"{Fore.CYAN} QUICK SCAN - Common Ports{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*70}")
print(f"Target: {Fore.YELLOW}{ip}{Style.RESET_ALL}")
print(f"Ports to scan: {Fore.YELLOW}{len(common_ports)}{Style.RESET_ALL}")
print(f"Started: {Fore.YELLOW}{datetime.now().strftime('%H:%M:%S')}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*70}\n")
for port in common_ports:
self.check_port(ip, port)
time.sleep(0.01)
print()
self.display_results(ip)
def display_results(self, ip):
"""Display scan results"""
if not self.open_ports:
print(f"\n\n{Fore.RED}{'='*70}")
print(f"{Fore.RED} SCAN RESULTS{Style.RESET_ALL}")
print(f"{Fore.RED}{'='*70}")
print(f"{Fore.RED}❌ No open ports found{Style.RESET_ALL}")
print(f"{Fore.RED}{'='*70}")
return
elapsed = time.time() - self.start_time
print(f"\n\n{Fore.GREEN}{'='*70}")
print(f"{Fore.GREEN} SCAN RESULTS{Style.RESET_ALL}")
print(f"{Fore.GREEN}{'='*70}")
print(f"Target: {Fore.YELLOW}{ip}{Style.RESET_ALL}")
print(f"Open ports: {Fore.GREEN}{len(self.open_ports)}{Style.RESET_ALL}")
print(f"Duration: {Fore.YELLOW}{elapsed:.2f}s{Style.RESET_ALL}")
print(f"{Fore.GREEN}{'='*70}\n")
print(f"{Fore.CYAN}{'PORT':<8} {'SERVICE':<15} {'BANNER'}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'-'*70}{Style.RESET_ALL}")
for port, service, banner in sorted(self.open_ports):
print(f"{Fore.GREEN}{port:<8} {service:<15} {banner[:50]}{Style.RESET_ALL}")
def validate_ip(ip):
"""Validate IP address"""
try:
ipaddress.ip_address(ip)
return True
except ValueError:
return False
def main():
parser = argparse.ArgumentParser(
description="Port Scanner - Multi-threaded network port scanner",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python scanner.py 192.168.1.1 --quick
python scanner.py 127.0.0.1 -p 20-100
python scanner.py 192.168.1.1 -p 80,443,8080
"""
)
parser.add_argument("ip", help="Target IP address")
parser.add_argument("-p", "--ports", help="Port range (20-100) or list (80,443,8080)")
parser.add_argument("--quick", action="store_true", help="Quick scan (common ports)")
parser.add_argument("-t", "--threads", type=int, default=50, help="Threads (default: 50)")
args = parser.parse_args()
if not validate_ip(args.ip):
print(f"{Fore.RED}Error: Invalid IP '{args.ip}'{Style.RESET_ALL}")
sys.exit(1)
scanner = PortScanner()
try:
if args.quick:
scanner.scan_common_ports(args.ip)
elif args.ports:
if '-' in args.ports:
start, end = map(int, args.ports.split('-'))
scanner.scan_port_range(args.ip, start, end, args.threads)
else:
ports = [int(p.strip()) for p in args.ports.split(',')]
scanner.total_ports = len(ports)
scanner.scanned_ports = 0
scanner.start_time = time.time()
print(f"{Fore.CYAN}{'='*70}")
print(f"{Fore.CYAN} PORT SCANNER v1.0{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*70}")
print(f"Target: {Fore.YELLOW}{args.ip}{Style.RESET_ALL}")
print(f"Ports: {Fore.YELLOW}{args.ports}{Style.RESET_ALL}")
print(f"{Fore.CYAN}{'='*70}\n")
for port in ports:
scanner.check_port(args.ip, port)
print()
scanner.display_results(args.ip)
else:
scanner.scan_common_ports(args.ip)
except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}[!] Scan interrupted{Style.RESET_ALL}")
sys.exit(0)
except Exception as e:
print(f"{Fore.RED}Error: {e}{Style.RESET_ALL}")
sys.exit(1)
if __name__ == "__main__":
main()