Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Reporting and Automation

Automating Scans and Comparing Results

Schedule regular Nmap scans of your own network, compare results with ndiff, detect new open ports and alert on changes, with Python change-detection examples.

A scan tells you the state of your network today. The real value for defenders comes from repeating the scan and looking at what changed: a new open port, a service that was upgraded, a host that appeared. A new open database port on a Friday evening is exactly what you want to hear about on Saturday morning. In this lesson you learn to schedule scans safely, compare two results and turn differences into alerts.

All of this is for networks you own or administer. Automated scanning needs the same authorisation and scope as manual scanning (see Legal and Ethical Scanning). Automation makes mistakes repeat quickly, so safety checks matter even more.

Nmap, cron and Task Scheduler cannot run here. Commands are shown read-only. The Python examples run on sample data and implement the comparison logic.

Designing a recurring scan

A good scheduled scan is small, predictable and recorded:

  1. Fixed scope in a file (targets.txt, used with -iL), with exclusions in --excludefile.
  2. Defined options, for example -sS -sV --open -T3 --max-rate 200 -oA.
  3. Dated output files (see Output Formats), written to a protected folder.
  4. A comparison step against the previous scan.
  5. An alert only if something meaningful changed.
  6. A log of when the scan started and finished, so that a silent failure is noticed too.
Terminal
#!/usr/bin/env bash
# Example script (read-only): weekly scan of our own office range
set -euo pipefail

day=$(date +%F)
out="/var/scans/office"
mkdir -p "$out"

nmap -sS -sV --open -T3 --max-rate 200 \
     -iL /etc/scans/office-targets.txt \
     --excludefile /etc/scans/office-exclude.txt \
     -oA "$out/$day"

prev=$(ls -1 "$out"/*.xml | grep -v "$day" | tail -n 1 || true)
if [ -n "$prev" ]; then
  ndiff "$prev" "$out/$day.xml" > "$out/$day.diff" || true
  if [ -s "$out/$day.diff" ]; then
    mail -s "Scan changes $day" security@example.test < "$out/$day.diff"
  fi
fi

Run it with cron on Linux (0 2 * * 6 /usr/local/bin/office-scan.sh is "02:00 every Saturday") or Task Scheduler on Windows. Run it from a machine placed correctly in the network (a scanner inside each segment sees more than one outside), and give the account only the privileges it needs.

Comparing with ndiff

Nmap ships with ndiff, a tool that compares two XML files and prints a short change report:

Terminal
# Example command (read-only)
ndiff scans/2026-11-05.xml scans/2026-11-12.xml
TEXT
-Nmap 7.98 scan initiated Thu Nov  5 02:00:01 2026
+Nmap 7.98 scan initiated Thu Nov 12 02:00:01 2026

 192.0.2.10:
-Not shown: 998 closed tcp ports (reset)
+Not shown: 997 closed tcp ports (reset)
+3306/tcp open  mysql   MySQL 8.0.36
-22/tcp   open  ssh     OpenSSH 9.5p1
+22/tcp   open  ssh     OpenSSH 9.6p1

Lines starting with - exist only in the old scan, + only in the new one. Here a MySQL port appeared (possibly a mistake or an unauthorised service) and OpenSSH was upgraded (good). ndiff -v shows unchanged lines too, and --xml writes the difference as XML.

Your own change detection

When you want to apply rules (for example "alert only on new open ports, ignore version bumps"), compare data structures in code. First turn each scan into a set of (host, port, protocol) entries plus service details.

Python Find new, closed and changed services

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rules, allow-lists and severity

Raw differences create noise. Add rules that reflect your policy:

  • Expected changes: an approved change request opens a port: record it in an allow-list so it is not flagged again.
  • Severity: a new database port or remote-desktop port is high; a version bump is info.
  • Baselines: keep a "golden" list of ports each host should expose, and compare scans with the baseline as well as with last week.
  • Context: include owner, environment (production or test) and the scan's command in the alert text.
Python Classify changes by severity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Running scans from Python

Python can launch Nmap with subprocess and read the XML from standard output. This read-only example shows the pattern; it needs Nmap installed and is not runnable on the site.

Python
import subprocess
import xml.etree.ElementTree as ET

def scan(targets_file: str) -> ET.Element:
    result = subprocess.run(
        ["nmap", "-sS", "--open", "-T3", "--max-rate", "200",
         "-iL", targets_file, "-oX", "-"],
        capture_output=True, text=True, check=True, timeout=3600,
    )
    return ET.fromstring(result.stdout)

Rules for such wrappers:

  • Pass arguments as a list, never build a shell string from user input (that is a command-injection risk).
  • Validate targets against the scope before calling Nmap (see the scope checker in the legal lesson).
  • Set a timeout and handle failures; a failed scan must alert too, because "no scan" is not "no changes".
  • Limit who can start scans, log every run and keep the output private.

Scaling up

For larger networks, teams split scans by segment, run them from several scanners and store the XML in a central place. Tools built on Nmap (for example vulnerability-management or asset-inventory systems) add dashboards, but the idea stays the same: repeat, compare, alert.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ndiff compare?

    ndiff reads two Nmap XML files and reports hosts and ports that were added, removed or changed.
  2. 2. In an ndiff report, what does a line starting with + mean?

    • marks content only in the first (old) file and + marks content only in the second (new) one.
  3. 3. Why should a failed scheduled scan produce an alert?

    If the scan silently fails, you would think nothing changed. Monitoring the scanner itself keeps the process trustworthy.
  4. 4. Why pass subprocess arguments as a list?

    A list is passed to the program directly. A shell string built from variable input could execute unintended commands.
  5. 5. What is a baseline in this context?

    A baseline states what should be exposed, so unexpected additions stand out, even if they have been there for weeks.

Summary

  • Schedule small, scoped, dated scans, save -oA output and compare with the previous result.
  • ndiff shows added and removed lines; your own code can apply rules, allow-lists and severity.
  • Wrap Nmap safely: argument lists, scope checks, timeouts, logs and alerts on failures.
  • Repeat, compare and alert is the core of network monitoring with Nmap.

Next: Project: A Network Inventory