-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathportsweep.py
51 lines (47 loc) · 1.42 KB
/
portsweep.py
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
import socket
import time
from typing import List, Tuple, Union, Optional, Dict
def sweep_host_ports(
ip: str,
ports: List[int],
timeout: float = 0.5,
grab_banner: bool = False,
detailed: bool = False
) -> Union[
List[int],
List[Tuple[int, str]],
List[Dict[str, Union[str, int, float]]]
]:
return [
result for port in ports
if (result := _scan_port(ip, port, timeout, grab_banner, detailed)) is not None
]
def _scan_port(
ip: str,
port: int,
timeout: float,
grab_banner: bool,
detailed: bool
) -> Optional[Union[int, Tuple[int, str], Dict[str, Union[str, int, float]]]]:
try:
start = time.perf_counter()
with socket.create_connection((ip, port), timeout=timeout) as sock:
banner = ""
if grab_banner:
try:
sock.settimeout(0.3)
banner = sock.recv(1024).decode(errors="ignore").strip() or "N/A"
except Exception:
banner = "N/A"
elapsed = round((time.perf_counter() - start) * 1000, 2)
if detailed:
return {
"ip": ip,
"port": port,
"status": "open",
"banner": banner if grab_banner else "",
"response_time_ms": elapsed
}
return (port, banner) if grab_banner else port
except Exception:
return None