Lightweight Vulnerability Scanner for Resourced-constrained Organizations

networkdiscovery.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import nmap
  2. import psutil
  3. import socket
  4. import ipaddress
  5. import pandas as pd
  6. from datetime import datetime
  7. import os
  8. # Set up data directory
  9. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  10. DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "data"))
  11. os.makedirs(DATA_DIR, exist_ok=True)
  12. excluded_prefixes = ("lo", "docker", "br-", "veth", "vmnet", "virbr")
  13. def get_ipv4_interfaces():
  14. ipv4_interfaces = []
  15. for name, addrs in psutil.net_if_addrs().items():
  16. for addr in addrs:
  17. if addr.family == socket.AF_INET:
  18. # Skip loopback or docker interfaces
  19. if name.startswith(excluded_prefixes):
  20. continue
  21. ipv4_interfaces.append((name, addr.address, addr.netmask))
  22. return ipv4_interfaces
  23. def network_discovery():
  24. ipv4_interfaces = get_ipv4_interfaces()
  25. if not ipv4_interfaces:
  26. print("No active IPv4 network interfaces found.")
  27. return
  28. nm = nmap.PortScanner()
  29. active_hosts = []
  30. for name, ip, netmask in ipv4_interfaces:
  31. network = ipaddress.IPv4Network((ip, netmask), strict=False)
  32. print(f"Discovering hosts in IP range {network} using interface {name}...")
  33. try:
  34. nm.scan(hosts=str(network), arguments='-sn -T4')
  35. except Exception as e:
  36. print(f"Error scanning {network}: {e}")
  37. continue
  38. discovered = nm.all_hosts()
  39. print(f"Found {len(discovered)} hosts on {network}")
  40. for host in discovered:
  41. active_hosts.append([host, datetime.now().strftime("%Y-%m-%d %H:%M:%S")])
  42. if active_hosts:
  43. columns = ['IP', 'Discovery Timestamp']
  44. df = pd.DataFrame(active_hosts, columns=columns)
  45. filename = "active_hosts.csv"
  46. output_file = os.path.join(DATA_DIR, filename)
  47. df.to_csv(output_file, index=False)
  48. print(f"Discovery complete. Results saved to {filename}")
  49. return df
  50. else:
  51. print("No active hosts found.")
  52. return None
  53. if __name__ == "__main__":
  54. network_discovery()