Lightweight Vulnerability Scanner for Resourced-constrained Organizations

portscanner.py 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import nmap
  2. import pandas as pd
  3. from datetime import datetime
  4. import os
  5. # Set up data directory
  6. BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  7. DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, "..", "data"))
  8. os.makedirs(DATA_DIR, exist_ok=True)
  9. def detailed_scan():
  10. active_hosts_path = os.path.join(DATA_DIR, "active_hosts.csv")
  11. try:
  12. active_hosts_df = pd.read_csv(active_hosts_path)
  13. except FileNotFoundError:
  14. print("File active_hosts.csv not found. Please run the network discovery script first.")
  15. return
  16. nm = nmap.PortScanner()
  17. scan_results = []
  18. start_time = datetime.now()
  19. print(f"Scan started at: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
  20. for index, row in active_hosts_df.iterrows():
  21. ip = row['IP']
  22. print(f"Scanning {ip} for detailed information...")
  23. try:
  24. nm.scan(ip, arguments='-p- -T5')
  25. except Exception as e:
  26. print(f"Error scanning {ip}: {e}")
  27. continue
  28. for host in nm.all_hosts():
  29. hostnames = [x['name'] for x in nm[host].get('hostnames', [])]
  30. mac_address = nm[host]['addresses'].get('mac', 'N/A')
  31. scan_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  32. for proto in nm[host].all_protocols():
  33. for port in nm[host][proto]:
  34. port_data = nm[host][proto][port]
  35. if port_data.get('state') != 'open':
  36. continue
  37. row = [
  38. ip,
  39. ', '.join(hostnames),
  40. mac_address,
  41. proto,
  42. port,
  43. port_data.get('name', ''),
  44. port_data.get('state', ''),
  45. port_data.get('product', ''),
  46. port_data.get('version', ''),
  47. port_data.get('extrainfo', ''),
  48. scan_timestamp
  49. ]
  50. scan_results.append(row)
  51. end_time = datetime.now()
  52. print(f"Scan finished at: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
  53. print(f"Total scan duration: {end_time - start_time}")
  54. if not scan_results:
  55. print("No open ports found.")
  56. return
  57. columns = [
  58. 'IP', 'Hostname', 'MAC Address', 'Protocol', 'Port', 'Name',
  59. 'State', 'Product', 'Version', 'Extra Info', 'Timestamp'
  60. ]
  61. detailed_df = pd.DataFrame(scan_results, columns=columns)
  62. filename = "detailed_scan_results.csv"
  63. output_file = os.path.join(DATA_DIR, filename)
  64. write_header = not os.path.exists(output_file)
  65. detailed_df.to_csv(output_file, mode='a', header=write_header, index=False)
  66. print(f"Scan results saved to {output_file}")
  67. print(detailed_df)
  68. if __name__ == "__main__":
  69. detailed_scan()