I made a ping sweep for the first time, and I want to do better. What do you think that I might be missing?
#! /usr/bin/env python3
import ipaddress
import platform
import socket
import subprocess
import time
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat
TIME_OUT = 3
def get_local_network():
"""Returns local IP,subnet mask and
other network informations"""
hostname = socket.gethostname()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(TIME_OUT)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
os_name = platform.system().lower()
mask = None
if "windows" in os_name:
output = subprocess.check_output("ipconfig", text=True)
for line in output.splitlines():
if ip in line:
continue
if "Subnet Mask" in line or "Alt Ağ Maskesi" in line:
mask = line.split(":")[1].strip()
break
else:
output = subprocess.check_output(
f"ip addr show | grep '{ip}'", shell=True, text=True
)
line = output.strip()
mask = line.split()[1].split("/")[1]
net = ipaddress.ip_network(f"{ip}/{mask}", strict=False)
return {
"hostname": hostname,
"host_ip": ip,
"subnet_mask": mask,
"network_ip": str(net.network_address),
"broadcast": str(net.broadcast_address),
"platform": os_name,
}
def icmp_ping(ip, subnet_mask):
"""
Pings specified IP address.
If ping successfull prints IP.
"""
try:
command = '-n' if platform.system().lower() == "windows" else '-c'
result = subprocess.call(
["ping", command, "1", ip],
stderr=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
)
if result == 0:
print(f"[+] Acitve: {ip}/{subnet_mask}")
except OSError as e:
print(f"An Error Occured: {e}")
except ValueError as e:
print(f"An Error Occured: {e}")
except PermissionError as e:
print(f"An Error Occured: {e}")
except FileNotFoundError as e:
print(f"An Error Occured: {e}")
def threader(net_ip, subnet_mask):
"""
Makes IP list for given IP and subnet mask.
And with ThreadPoolExecutor pings all IP's.
"""
ip_count = 32 - int(subnet_mask)
total_ip = (2**ip_count) - 2
base_ip = net_ip.rsplit(".", 1)[0]
ip_list = [f"{base_ip}.{i}" for i in range(1, total_ip + 1)]
with ThreadPoolExecutor(max_workers=40) as executor:
executor.map(icmp_ping, ip_list, repeat(subnet_mask))
def main():
info_package = get_local_network()
print(f"HOST:{info_package['hostname']}")
print(f"Host IP:{info_package['host_ip']}")
print(f"Network IP Address:{info_package['network_ip']}")
print(f"OS:{info_package['platform']}")
threader(info_package["network_ip"], info_package["subnet_mask"])
print("IP Scan Finished. Glad you were here :)")
main()
nmap. Note that scanning networks without permission can get you in trouble. \$\endgroup\$