Repository navigation
Expand file tree
/
Copy pathscanner.py
More file actions
278 lines (224 loc) · 8.11 KB
/
Copy pathscanner.py
File metadata and controls
278 lines (224 loc) · 8.11 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
import subprocess
import socket
from concurrent.futures import ThreadPoolExecutor
import datetime
import sqlite3
import time
def ping_host(ip):
result = subprocess.run(
["ping", "-n", "1", "-w", "1000", ip],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
return result.returncode == 0
def get_hostname(ip):
try:
return socket.gethostbyaddr(ip)[0]
except socket.herror:
return "Unknown"
COMMON_PORTS = {
21: "FTP",
22: "SSH",
23: "Telnet",
80: "HTTP",
443: "HTTPS",
445: "SMB",
3389: "RDP",
}
def scan_ports(ip):
open_ports = []
for port in COMMON_PORTS:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((ip, port))
if result == 0:
open_ports.append(port)
sock.close()
return open_ports
def get_netbios_name(ip):
try:
result = subprocess.run(
["nbtstat", "-A", ip],
capture_output=True,
text=True,
timeout=2
)
for line in result.stdout.splitlines():
if "<00>" in line and "UNIQUE" in line:
return line.split()[0].strip()
return "Unknown"
except Exception:
return "Unknown"
def check_ip(ip, my_ip):
if ping_host(ip):
if ip == my_ip:
hostname = socket.gethostname()
else:
hostname = get_hostname(ip)
if hostname == "Unknown":
hostname = get_netbios_name(ip)
ports = scan_ports(ip)
port_info = ", ".join(f"{p}({COMMON_PORTS[p]})" for p in ports) if ports else "none"
print(f"{ip} is alive - {hostname} - open ports: {port_info}")
return (ip, hostname, ports)
return None
def scan_network(subnet, my_ip):
ip_list = [f"{subnet}.{i}" for i in range(1, 255)]
alive_hosts = []
with ThreadPoolExecutor(max_workers=20) as executor:
results = executor.map(lambda ip: check_ip(ip, my_ip), ip_list)
for result in results:
if result:
alive_hosts.append(result)
return alive_hosts
def get_local_subnet():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
local_ip = s.getsockname()[0]
finally:
s.close()
subnet = ".".join(local_ip.split(".")[:3])
return subnet, local_ip
def get_arp_table(subnet):
"""
Read the OS's ARP cache and return {ip: mac} for devices on this subnet.
Catches devices that block ping (ICMP) but have still communicated on
the network recently, since ARP is required for any local traffic to work at all.
"""
import re
try:
result = subprocess.run(["arp", "-a"], capture_output=True, text=True, timeout=5)
except Exception:
return {}
devices = {}
for line in result.stdout.splitlines():
match = re.match(r"\s*(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F-]{17})\s+(\w+)", line)
if match:
ip, mac, entry_type = match.groups()
if ip.startswith(subnet) and entry_type.lower() == "dynamic":
devices[ip] = mac
return devices
def init_db():
"""Create both tables if they don't already exist."""
conn = sqlite3.connect("scanner.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS scan_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT,
hostname TEXT,
open_ports TEXT,
scan_time TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS device_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ip TEXT,
hostname TEXT,
event TEXT,
event_time TEXT
)
""")
conn.commit()
conn.close()
def get_last_scan_data():
"""Return {ip: hostname} for every device seen in the most recent scan."""
conn = sqlite3.connect("scanner.db")
cursor = conn.cursor()
cursor.execute("SELECT MAX(scan_time) FROM scan_log")
last_time = cursor.fetchone()[0]
if last_time is None:
conn.close()
return {}
cursor.execute("SELECT ip, hostname FROM scan_log WHERE scan_time = ?", (last_time,))
data = {row[0]: row[1] for row in cursor.fetchall()}
conn.close()
return data
def save_scan(devices, scan_time):
conn = sqlite3.connect("scanner.db")
cursor = conn.cursor()
for ip, hostname, ports in devices:
port_str = ",".join(str(p) for p in ports)
cursor.execute("""
INSERT INTO scan_log (ip, hostname, open_ports, scan_time)
VALUES (?, ?, ?, ?)
""", (ip, hostname, port_str, scan_time))
conn.commit()
conn.close()
def get_last_seen(ip):
conn = sqlite3.connect("scanner.db")
cursor = conn.cursor()
cursor.execute("SELECT MAX(scan_time) FROM scan_log WHERE ip = ?", (ip,))
result = cursor.fetchone()[0]
conn.close()
return result
def log_event(ip, hostname, event, event_time):
"""Record a 'connected' or 'disconnected' event for a device."""
conn = sqlite3.connect("scanner.db")
cursor = conn.cursor()
cursor.execute("""
INSERT INTO device_events (ip, hostname, event, event_time)
VALUES (?, ?, ?, ?)
""", (ip, hostname, event, event_time))
conn.commit()
conn.close()
def get_device_events(ip):
"""Return the full connect/disconnect history for one device."""
conn = sqlite3.connect("scanner.db")
cursor = conn.cursor()
cursor.execute("""
SELECT event, event_time FROM device_events
WHERE ip = ? ORDER BY event_time
""", (ip,))
rows = cursor.fetchall()
conn.close()
return rows
if __name__ == "__main__":
init_db()
subnet, my_ip = get_local_subnet()
print(f"Your IP: {my_ip} | Monitoring subnet: {subnet}.0/24")
print("Scanning every 5 minutes. Press Ctrl+C to stop.\n")
try:
while True:
previous_data = get_last_scan_data()
previous_ips = set(previous_data.keys())
devices = scan_network(subnet, my_ip)
responding_ips = {d[0] for d in devices}
arp_devices = get_arp_table(subnet)
for ip, mac in arp_devices.items():
if ip not in responding_ips:
print(f"{ip} found via ARP only (blocks ping) - MAC: {mac}")
devices.append((ip, f"Unknown (MAC {mac})", []))
current_data = {ip: hostname for ip, hostname, ports in devices}
all_ips = {f"{subnet}.{i}" for i in range(1, 255)}
alive_ips = {d[0] for d in devices}
unused_ips = sorted(all_ips - alive_ips, key=lambda ip: int(ip.split(".")[-1]))
connected = alive_ips - previous_ips
disconnected = previous_ips - alive_ips
scan_time = datetime.datetime.now().isoformat(timespec="seconds")
save_scan(devices, scan_time)
for ip in connected:
log_event(ip, current_data[ip], "connected", scan_time)
for ip in disconnected:
log_event(ip, previous_data[ip], "disconnected", scan_time)
print(f"--- Scan at {scan_time} ---")
print(f"Found {len(devices)} device(s):")
for ip, hostname, ports in devices:
port_info = ", ".join(f"{p}({COMMON_PORTS[p]})" for p in ports) if ports else "none"
print(f" {ip} - {hostname} - ports: {port_info}")
print(f"\nUnused IPs ({len(unused_ips)}): {', '.join(unused_ips)}")
if connected:
print(f"\n🟢 Newly connected:")
for ip in sorted(connected):
print(f" {ip} - {current_data[ip]}")
if disconnected:
print(f"\n🔴 Disconnected:")
for ip in sorted(disconnected):
last_seen = get_last_seen(ip)
print(f" {ip} - {previous_data[ip]} - last seen: {last_seen}")
print(f"\nSleeping 5 minutes until next scan...\n")
time.sleep(300)
except KeyboardInterrupt:
print("\nMonitoring stopped by user. Goodbye!")