To compare two Nmap scans, save each run as XML and run ndiff before.xml after.xml. Read the differences only after checking that both runs used the same target, port list, scan method and network path. A changed report is an observation to investigate; it does not, by itself, prove that a service changed.
Table of Contents

This guide is for learners troubleshooting an owned Kioptrix VM or another explicitly authorized local lab. It turns a confusing “the ports were different yesterday” moment into a small, repeatable comparison. You will finish with two XML files, a difference report and a decision record that explains what remains unknown.
Documentation checked: November 16, 2026. Commands are a worked procedure for a local Linux lab. Illustrative results below are teaching examples, not measurements from a Kioptrix VM tested for this article.
Prepare two comparable scans

Imagine TCP port 80 appears open in one report and filtered in another. Perhaps a firewall rule changed. Perhaps Kali used a different interface after a VPN connected. Perhaps the address now belongs to another VM. Those explanations require different next steps, even though the screen looks similar.
Start by writing one question: “Does the same TCP port respond differently from the same Kali VM after this named lab event?” Replace “named lab event” with your actual event, such as restoring a snapshot or restarting the target. If several things changed at once, record that limitation instead of choosing a convenient explanation.
- Confirm the target VM and its current address using the hypervisor configuration, guest console or known DHCP lease. An old screenshot is not sufficient identity evidence.
- Keep the vulnerable target on the intended lab segment. Review extra adapters and routes before probing it.
- Use a small explicit port list for the comparison. This is a diagnostic sample, not an inventory of every reachable service.
- Keep the original files. Use a new filename for each repeat rather than overwriting the evidence you are trying to explain.
If the network boundary or target address is uncertain, start with Kioptrix network setup and DHCP checks. Comparing output cannot repair an unidentified target.
Save XML and compare Nmap scans with Ndiff
Nmap’s Ndiff reference specifies two Nmap XML inputs. Ndiff can report differences in host and port states, detected service information, OS matches and script output. Its text format marks removed observations with a minus sign and added observations with a plus sign. Keep the older file first.
1. Check the tools and local context
nmap --version
ndiff --help
ip -br addr
ip route
If ndiff is missing on Kali, the official Kali Nmap tools page lists the Ndiff package. Install it from your configured Kali repositories using sudo apt install ndiff. Complete any repository maintenance separately from the comparison and record the tool versions afterward.
2. Set your verified target and capture a baseline
The address below is an example. Replace it with the address you have verified belongs to your authorized lab VM. Do not copy it as a presumed Kioptrix default.
LAB_TARGET=192.168.56.101
mkdir -p kioptrix-scan-compare
cd kioptrix-scan-compare
nmap -n -sT -p 22,80,139,443,445 --reason -oX before.xml "$LAB_TARGET"
Preserve earlier sessions: the short filenames below are for one comparison. Before repeating the exercise, use a new directory or new filenames so you do not overwrite an existing baseline. Confirm that cd succeeded before running the scan.
This deliberately uses an explicit TCP connect scan and five named ports. Keep that scan type and port list unchanged for the repeat. The list does not assert that every Kioptrix release exposes these ports. It also says nothing about UDP or TCP ports outside the list.
The official output reference documents -oX for XML. Giving a terminal transcript an .xml extension does not convert it into Nmap XML. Wait for the scan to finish and resolve any error before treating the file as a baseline.
3. Repeat under the intended conditions
After your recorded event, verify target identity and routing again. If the address changed, update your notes and establish a fresh comparison pair for that verified identity rather than treating an address change as a service change.
nmap -n -sT -p 22,80,139,443,445 --reason -oX after.xml "$LAB_TARGET"
ndiff before.xml after.xml
These commands omit service-version detection, OS detection and NSE scripts so the first question stays narrow: did the observed TCP states change? If your question is about a banner, add the same version-detection options to both future scans and save a new matched pair. Do not compare a simple port scan with a more detailed probe and call the extra detail a newly installed service.
4. Save the report and its exit status
ndiff before.xml after.xml > changes.txt
NDIFF_STATUS=$?
printf 'Ndiff exit status: %s\n' "$NDIFF_STATUS"
cat changes.txt
Run this sequence in a normal interactive shell; a script using set -e needs explicit handling for a difference result. Ndiff returns 0 for equality in the aspects it compares, 1 for differences and 2 for a runtime error. Capture the status immediately after Ndiff. A later command replaces $?. Status 1 is not a failed installation.
Understand the options in the comparison command
Keep a small, deliberate probe profile. These options answer different questions; adding a flag to only one run changes the experiment.
| Option | Purpose here | Comparison caution |
|---|---|---|
-n | Skip reverse DNS lookup. | An IP address still needs identity evidence. |
-sT | Explicit TCP connect scan. | Keep the method fixed; do not silently switch to a privileged default. |
-p 22,80,139,443,445 | Limit the probe to five TCP ports. | Do not generalize to other ports or UDP. |
--reason | Include the reason for a reported state. | A reason helps inspect an observation; it does not prove its cause. |
-oX before.xml | Write Nmap XML to the named file. | Use a fresh name or session directory to preserve earlier evidence. |
The official scan-technique reference explains the connect method. This tutorial specifies it to keep the method visible and consistent, not to claim it is always the best technique.
Do not confuse two verbose modes: nmap -v affects scan output; ndiff -v before.xml after.xml includes unchanged hosts and ports in the comparison. The latter reads saved files and does not launch another scan. Use it when a short report lacks the context you need.
Check XML completion before running Ndiff
Before interpreting a difference, check that you have two completed Nmap runs. A readable XML document is only a format check: a scan can finish successfully while discovering no live hosts. Conversely, a truncated file can fail before Ndiff has anything meaningful to compare.
The following optional Python 3 helper reads local files only. Run it in the directory containing your own scan files. It checks the Nmap root and successful completion marker, then prints the recorded command, coverage and host counts for manual review. It does not verify target ownership, establish host identity, validate every field against a DTD or certify that the two scans are comparable.
python3 - before.xml after.xml <<'PY'
import sys
import xml.etree.ElementTree as ET
for filename in sys.argv[1:]:
try:
root = ET.parse(filename).getroot()
except (OSError, ET.ParseError) as error:
print(f"{filename}: unreadable XML: {error}")
raise SystemExit(2)
finished = root.find("./runstats/finished")
if root.tag != "nmaprun" or finished is None:
print(f"{filename}: missing Nmap root or completion record")
raise SystemExit(2)
if finished.get("exit") != "success":
print(f"{filename}: scan did not record successful completion")
raise SystemExit(2)
print(f"\nFILE: {filename}")
print("Nmap version:", root.get("version", "unknown"))
print("Command:", root.get("args", "unknown"))
print("Host counts:", root.find("./runstats/hosts").attrib
if root.find("./runstats/hosts") is not None else "unknown")
for scan in root.findall("./scaninfo"):
print("Coverage:", scan.attrib)
PYRead the output before proceeding: different coverage or scan types mean you need to explain that mismatch. Zero live hosts means you should investigate discovery and target readiness. Matching metadata still leaves the network path and VM identity to be confirmed from your notes. If an older file lacks the expected completion marker, inspect its provenance rather than editing the XML to force it through this check.
Choose the next action from the Ndiff result
Use the exit status to decide whether to read a comparison or fix an input problem. In an automated shell script, explicitly handle status 1; otherwise a difference can be mistaken for a failed job.
if ndiff before.xml after.xml > changes.txt 2> ndiff-errors.txt; then
NDIFF_STATUS=0
else
NDIFF_STATUS=$?
fi
case "$NDIFF_STATUS" in
0) printf '%s\n' 'No differences in the aspects Ndiff compares.' ;;
1) printf '%s\n' 'Differences found; review changes.txt.' ;;
*) printf '%s\n' 'Comparison error; review ndiff-errors.txt.' ;;
esacThis saves normal output and diagnostics separately. A runtime error is not evidence of a target change. Preserve both files, check the error, and rerun only after resolving the input issue. This wrapper assumes the two input scans have already completed.
For a reported change: first locate the affected host, then the exact port and protocol. Compare the earlier and later states, and check coverage before proposing an explanation. If only the scan heading or time differs in displayed context, do not turn that into a service-change claim. The exit status concerns the aspects Ndiff compares, not byte-for-byte equality of the XML files.
For an unchanged comparison: retain the result as a baseline with its time window. It is useful evidence for a narrow question, such as whether those five TCP observations stayed consistent. It is not a reason to stop investigating an application failure outside that scope.
Seven checks before trusting a scan difference
Use this table before writing “the target changed.” The purpose is to find the first comparison condition you cannot support with evidence.
| Check | What to match | What to do if it differs |
|---|---|---|
| 1. Target identity | VM name, current address and identity evidence | Resolve a lease change, clone or address collision before continuing. |
| 2. Network vantage point | Kali interface, route, VPN state and virtual network | Label the result as a path comparison or restore the original path. |
| 3. Port and protocol coverage | Same explicit TCP or UDP set | Collect a matched pair. An unscanned port has no earlier state to compare. |
| 4. Probe behavior | Scan type, discovery settings, privileges and detection options | Repeat with the original method rather than adding flags mid-pair. |
| 5. Tool context | Nmap version and relevant configuration or data changes | Separate a tool update from a target-side experiment. |
| 6. VM state and timing | Snapshot, boot completion, service readiness and intervening actions | Record the event and wait for the intended ready state. |
| 7. File completeness | Finished scans, readable XML and original command lines | Preserve the failed artifact, fix the error and collect a new run. |
Two identical command lines are useful, but they cannot prove that the path or target stayed identical. Conversely, changing a filename is harmless to comparability. Focus on conditions that could change the observation.
Interpret the result without overstating it
The following short fragment is illustrative, with scan headers and other context omitted:
-80/tcp open http
+80/tcp filtered http
The supported statement is: “The recorded observation for TCP 80 changed from open to filtered between these runs.” The unsupported shortcut is: “Apache was removed.” Filtering and application availability are different questions.
Nmap’s port-state guide explains that port states reflect what the scanner observes from its position. An open result indicates an accepting service; closed indicates a reachable port without a listening application; filtered means Nmap cannot determine whether it is open because of filtering. A state label is not a vulnerability verdict.
| Difference | A bounded interpretation | Next useful check |
|---|---|---|
| Open becomes closed | The later probe received behavior classified as closed. | Confirm the VM identity and, if you administer it, inspect listener state. |
| Open becomes filtered | The later path did not expose an open/closed answer to that probe. | Compare routes, adapters and filtering configuration before changing services. |
| A version string appears | The later report contains additional identification detail. | Check whether both runs used the same detection settings. |
| A host appears or disappears | The files differ in recorded host presence. | Check scope, discovery behavior, boot state and DHCP identity. |
| No compared differences | The compared observations match. | Keep the result limited to the tested ports, methods and time window. |
If you need packet-level context, continue with Wireshark evidence review. A packet capture can help explain a particular exchange; it still needs the correct interface, timing and endpoint identity.
Use three runs to separate baseline noise from an event
A before/after pair can accidentally compare a stable result with a transient one. A stronger learning exercise adds an unchanged repeat before the event. The three-run method below is an editorial workflow, not a built-in Ndiff feature or a guarantee of causation.
Save the first completed scan and its context.
Repeat the same probe without an intentional lab change.
Record one event, reverify identity and collect a third run.
- Save A as
baseline-a.xmland B asbaseline-b.xml, using the same command options. - Compare A with B. If unexplained differences already exist, investigate them before attributing later changes to your event.
- Record the event precisely. “Restored snapshot clean-boot” is more useful than “fixed VM.”
- Save C as
after-event.xmland compare B with C. - Repeat the affected observation if needed, keeping the original files and naming the new run separately.
ndiff baseline-a.xml baseline-b.xml
ndiff baseline-b.xml after-event.xml
If A and B match and C differs, the event becomes a reasonable hypothesis to investigate. It remains a hypothesis: background service startup, resource pressure or an unnoticed path change can still affect the result. Check one explanation at a time.
For rollback planning, see Kioptrix snapshots and recovery. Keep scan files outside a target snapshot that you might restore. Otherwise the rollback can remove the very evidence you intended to compare.

Copy this scan-comparison decision record
Paste this into your lab notes. Replace every blank with an observation or “unknown.” The record is useful even when the outcome is inconclusive.
Question:
Ndiff version / package version if available:
Authorized target VM and identity evidence:
Current target IP / MAC where available:
Kali interface and route to target:
Hypervisor network and snapshot:
Nmap version:
Exact command and covered ports/protocols:
A: filename, start/end time, completion status:
B: filename, start/end time, completion status:
A-to-B differences and unresolved noise:
Recorded event between B and C:
C: filename, start/end time, completion status:
B-to-C difference and Ndiff exit status:
Supported observation:
Possible explanations:
Next single check:
What this comparison does not establish:
Example conclusion: “Two unchanged five-port TCP scans matched. After the recorded snapshot restore, TCP 80 was reported closed instead of open. Target identity and route were rechecked. The comparison does not establish why the listener changed; guest service state is the next check.” This is an example of wording, not a reported experiment.
Use the broader Kioptrix evidence tracking guide to connect the files and the conclusion to the rest of your investigation.
Worked review: decide what the difference supports
Consider this fictional notebook entry: the first scan reports TCP 80 open, the second reports it filtered, and the learner remembers restarting a VM between runs. The two files alone do not tell you which VM restarted, whether the scanner changed networks, or whether the address was reassigned. Begin the review by separating recorded facts from remembered context.
First, preserve the pair. Keep before.xml, after.xml and changes.txt together with the original command lines. Write down which file you believe is earlier and what supports that ordering. If the event time is uncertain, mark it uncertain. Do not rename the files to imply a sequence you cannot establish. A tidy filename is useful organization; it is not independent evidence.
Second, test the identity assumption. Consult the target console or your existing hypervisor and lease records. If the earlier identity was never recorded, say so in the conclusion. Verifying the current VM is useful, but it does not retroactively prove which machine answered yesterday. This gap may make the old pair unsuitable for a target-change claim, while still leaving it useful as a troubleshooting example.
Third, inspect the comparison conditions. Read the saved commands side by side. Confirm the same covered ports and intended probe method, then consult your notes for interfaces, routes and VM readiness. If one run followed a VPN connection or snapshot restore, record that event as a possible explanation. Avoid silently changing several settings before collecting the next observation; that makes the resulting improvement harder to interpret.
Fourth, choose one next observation. Suppose current identity and path are established, but service readiness remains unknown. Check that condition through the guest console if you administer the VM. Alternatively, collect another matched scan after the intended ready state and save it as a separate file. Name the question before doing the check, and retain an unexpected result with the same care as an expected one.
Finally, write a bounded decision. A useful entry might read: “The two saved reports disagree on TCP 80. Earlier target identity was not recorded, so this pair cannot establish a change on the same VM. Current identity and route are documented. I will collect a new baseline and an unchanged repeat before testing another event.” This conclusion makes the next session easier to reproduce without pretending the uncertainty disappeared.
If the next matched pair agrees, preserve that result as your new starting point. If it disagrees, instability itself becomes the question. Either outcome improves the record because it narrows what you can responsibly claim and identifies the next check. None of the fictional observations in this example is a measured result from this article.
Practice: three differences, three different conclusions
These fictional mini-cases test interpretation without scanning anything. Choose a conclusion before opening each answer.
Case 1: TCP 443 appears only in the later scan. Is it a new service?
The earlier command covered TCP 22 and 80; the later one also covered 443. The supported conclusion is unequal coverage. You have no earlier observation for 443. Collect a matched pair before claiming a new listener.
Case 2: both scans show TCP 80 open, but a version string appears later. Was software installed?
The later command added version detection. The supported conclusion is additional identification detail under a different probe profile. A software-change claim needs a matched detection method and supporting evidence.
Case 3: A and B match; C reports TCP 80 closed after a recorded restart. What comes next?
The repeated baseline strengthens the observation, but the restart is still a hypothesis about the cause. Recheck VM identity and readiness, then inspect the listener through the guest console if you administer it. Record the finding separately from your explanation.
A good stopping point: you can identify the two inputs, explain what was comparable, quote the changed observation and name one next check. If you cannot do that yet, record the uncertainty instead of expanding the scan until a preferred answer appears.
Troubleshooting and frequently asked questions
Why does Ndiff reject my file?
Check the path, permissions and actual file contents. It expects Nmap XML, not a screenshot, a copied terminal report or a text file renamed with an XML extension. An interrupted scan can leave an incomplete artifact. Preserve it for diagnosis and create a new completed run.
Can I compare a fast scan with a full port scan?
You can compare the XML files, but their unequal coverage limits what you can infer. A port newly included in the second scan is not evidence that a listener was newly enabled. Use equal explicit port lists for a service-state experiment, and label wider coverage as a separate inventory task.
Should I add -Pn when the target disappears?
First verify the address, VM power state and route. Changing host-discovery behavior changes the comparison conditions. If you choose a new discovery policy for diagnosis, document it and use it consistently in a new pair. A flag cannot confirm that the address still belongs to the intended VM.
Does no difference mean that the VM is secure?
No. Equality concerns recorded observations Ndiff compares. The commands here cover five TCP ports, without a vulnerability assessment. They do not establish patch status, authorization controls, absence of malware or behavior on untested ports.
Can I use a normal text diff instead?
A text diff is useful for reviewing literal files. Ndiff is designed for Nmap XML observations, so it is the more direct tool for this task. Keep the raw inputs either way. Neither tool identifies the cause of a change.
What if results change on every repeat?
Stop adding variables. Verify target identity, network path, VM readiness, scan completion and resource conditions. Record the instability as the finding to investigate. Do not choose the most convenient run and discard the rest.
Official references and method limits
- Ndiff reference guide — accepted inputs, output markers and exit codes.
- Nmap output reference — XML output and saved file formats.
- Nmap port scanning basics — interpretation of observed port states.
- Kali Nmap tools documentation — package and command availability.
The commands and flag meanings were checked against these primary sources. No live Kioptrix scan, performance benchmark or release-specific port inventory was performed for this article. Run the procedure in your own authorized environment and retain the evidence for any conclusion you publish.
Start with the comparison record