← Back to Automation Hub

Chapter 23: Automated Network Audits

As a System Architect, you must ensure that your network is secure. Manual scanning is slow. Today, we will automate the process of identifying open ports and active services using Nmap and Python.

SECURITY NOTE: Only scan networks and devices that you own or have explicit permission to audit. Unauthorized scanning is unethical and often illegal.

1. Equipping the Matrix

First, we need to install the necessary tools in our Debian environment:

sudo apt update && sudo apt install nmap python3-nmap -y

2. Building the Automated Scanner

We will write a Python script that scans a specific IP range and logs the results into a file automatically. Create: nano net_audit.py

import nmap
import datetime

# Initialize Port Scanner
nm = nmap.PortScanner()
target = "127.0.0.1" # Change to your local IP

print(f"--- SCANNING TARGET: {target} ---")
nm.scan(target, '21-443')

with open("audit_log.txt", "a") as f:
    f.write(f"\nAudit Date: {datetime.datetime.now()}\n")
    for host in nm.all_hosts():
        f.write(f"Host: {host} ({nm[host].hostname()})\n")
        f.write(f"State: {nm[host].state()}\n")
        for proto in nm[host].all_protocols():
            lport = nm[host][proto].keys()
            for port in lport:
                f.write(f"Port: {port}\tState: {nm[host][proto][port]['state']}\n")

print(">>> Audit Complete. Results saved to audit_log.txt")
    

3. Automating the Audit

To make this truly automated, you can combine this with a Bash script or a Cron job to run every weekend and keep a history of your network's security posture.

Next Chapter: Cron Job Mastery (Coming Soon)