I created a poor man’s solution to CSC 1 by writing a Python script that uses nmap to scan, ndiff to compare the scan results against a baseline (an nmap scan file of authorized devices), and then Python’s smtplib to send me an email if a device is on the network that is not on the baseline.
import os import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText def discover_and_diff(): """Scans and compare results against a baseline""" os.system("nmap -sn 192.168.0.0/24 -oX inventory_current.xml") os.system("ndiff inventory_baseline.xml inventory_current.xml > inventory_diff.txt") def read_diff(): """Opens the diff and records the lines with added differences""" with open('inventory_diff.txt') as file_object: contents = [] for line in file_object: if line.startswith("+") and line[1:5] != "Nmap": contents.append(line[1:]) scan_diff_result = '\n'.join(contents) return scan_diff_result def send_diff_email(): """Calls read_diff, and sends an email if new hosts are present""" scan_alert = read_diff() if bool(scan_alert) == True: to_addr = 'recipient@example.com' from_addr = 'sender@gmail.com' msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = 'Inventory Scan Alert' body = scan_alert smtp_obj = smtplib.SMTP('smtp.gmail.com', 587) smtp_obj.ehlo() smtp_obj.starttls() smtp_obj.login('my_email@.gmail.com', 'my_password') text = msg.as_string() smtp_obj.sendmail(from_addr, to_addr, text) else: print("No new devices. All secure.") def main(): discover_and_diff() send_diff_email() if __name__ == '__main__': main()