In the life of a System Architect, security is not a one-time event—it is a continuous process. Manual scanning is inefficient and prone to human error. Today, we scale our security operations by automating port identification and service discovery using Nmap and Python.
Before we write our logic, we must ensure our environment has the necessary binaries. Run this in your Termux or Linux terminal:
sudo apt update && sudo apt install nmap python3-pip -y pip install python-nmap
This Python script doesn't just scan; it logs historical data. This allows you to track changes in your network posture over time. Create net_audit.py:
import nmap
import datetime
# Initialize the Port Scanner engine
nm = nmap.PortScanner()
target = "127.0.0.1" # Target: Localhost or your Network Range
print(f"--- INITIATING AUDIT: {target} ---")
nm.scan(target, '21-443')
# Automated Logging System
with open("audit_log.txt", "a") as f:
f.write(f"\n--- Audit Session: {datetime.datetime.now()} ---\n")
for host in nm.all_hosts():
f.write(f"Host ID: {host} | Hostname: {nm[host].hostname()}\n")
f.write(f"Status: {nm[host].state().upper()}\n")
for proto in nm[host].all_protocols():
ports = nm[host][proto].keys()
for port in ports:
state = nm[host][proto][port]['state']
f.write(f" [+] Port: {port}/{proto} | State: {state}\n")
print(">>> SUCCESS: Results archived in audit_log.txt")
To achieve true automation, move this script into a Cron Job. This allows the system to audit itself every midnight while you sleep, sending the logs to your repository automatically.
To run audits 24/7 without keeping your mobile device active, I recommend deploying these scripts on a high-uptime Cloud Server.
(Recommended for Chapter 23 tasks)
[ GET $200 FREE CLOUD CREDIT ]*Support the Academy by using our partner links.
SEVEN33_ACADEMY | DOCUMENTATION_ID: CH23_NET_AUDIT
Next: Chapter 24 - Cron Job Mastery