-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscanner.py
More file actions
73 lines (60 loc) · 1.82 KB
/
scanner.py
File metadata and controls
73 lines (60 loc) · 1.82 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
import subprocess
import ipaddress
import json
from datetime import datetime
# Validate - Ask for subnet and validate it
while True:
# Ask user for a subnet
subnet = input("Enter a subnet (e.g. 192.168.1.0/30): ")
try:
# Convert the text into a network object
network = ipaddress.ip_network(subnet, strict=False)
break
except ValueError:
print("Invalid subnet. Please try again...")
# New list for storing the results and starting timestamp
results = []
scan_start = datetime.now().isoformat(timespec="seconds")
# Function to ping one IP
def ping_ip(ip_str):
try:
result = subprocess.run(
["ping", "-n", "1", "-w", "2000", ip_str],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=3
)
output = result.stdout
if "TTL" in output:
status = "UP"
else:
status = "DOWN"
except subprocess.TimeoutExpired:
status = "DOWN (timeout)"
except Exception as e:
status = f"ERROR: {str(e)}"
# Main loop: Scan all usuable IP addresses
for ip in network.hosts():
ip_str = str(ip)
print("Pinging: ", ip_str)
status = ping_ip(ip_str)
print(ip_str, " is ", status)
print("----------------------")
# Store results as an object
results.append({
"ip: ": ip_str,
"status ": status,
"timestamp: ": datetime.now().isoformat(timespec="seconds")
})
# JSON structure
output_data = {
"subnet: ": subnet,
"scan_started_at: ": scan_start,
"scan_finished_at: ": datetime.now().isoformat(timespec="seconds"),
"results :": results
}
# Save to JSON file
with open("results.json", "w") as file:
json.dump(results, file, indent=4)
print("Scan complete. Results saved to results.json")