I rebuilt a staging box from an old notes file last month and only found out afterwards how much had quietly changed. Since then I capture the installed package list on every server before touching it, and a short Python script diffs the two lists in one pass.
The idea is simple: dpkg-query gives you a tab-separated name/arch/version list on any Debian or Ubuntu machine, and the script does set math on package names plus a version string comparison. It reports three things – packages missing on the new box, packages the new box gained, and packages where the version drifted. Exit code is 0 when clean and 1 when there is drift, so it drops straight into cron. If you want a broader look at what each package does security-wise, I covered patching the gaps with OSV.dev earlier.
Reference material: dpkg-query manpage and OSV.dev for the CVE follow-up.

Capture the package list on each server
On each server, as root or your own user (dpkg-query needs no elevated rights to read the status database):
dpkg-query -W -f='${Package}\t${Architecture}\t${Version}\n' | awk -F'\t' '$3 != ""' | sort > new-server.txtThe script
This is the exact file that ran in my sandbox, no cleverness in it: plain dicts, sorted set differences, and one guard against the broken lines dpkg emits for meta-packages. The demo lists below are synthetic, a hand-edited copy of a real capture from an Ubuntu 26.04 box, so nobody is confused about which server is which.
#!/usr/bin/env python3
"""pkgdiff.py - compare two dpkg package lists and report the drift."""
import argparse
import sys
from pathlib import Path
def load_list(path):
"""Parse a tab-separated 'namearchversion' list from dpkg-query."""
pkgs = {}
for lineno, line in enumerate(path.read_text().splitlines(), 1):
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split("\t")
if len(parts) != 3 or not parts[2]:
sys.exit(f"{path}:{lineno}: bad line (need name/arch/version, tab-separated): {line!r}")
pkgs[parts[0]] = {"arch": parts[1], "ver": parts[2]}
return pkgs
def main():
ap = argparse.ArgumentParser(description="Diff two dpkg -W package lists.")
ap.add_argument("list_a", type=Path, help="reference list (e.g. the server you are leaving)")
ap.add_argument("list_b", type=Path, help="target list (e.g. the rebuild you are checking)")
ap.add_argument("--quiet", action="store_true", help="summary lines only")
args = ap.parse_args()
a, b = load_list(args.list_a), load_list(args.list_b)
only_a = sorted(set(a) - set(b))
only_b = sorted(set(b) - set(a))
differ = sorted(n for n in set(a) & set(b) if a[n]["ver"] != b[n]["ver"])
print(f"pkgdiff: {args.list_a.name} ({len(a)} pkgs) vs {args.list_b.name} ({len(b)} pkgs)")
print(f" only in {args.list_a.name}: {len(only_a)}")
print(f" only in {args.list_b.name}: {len(only_b)}")
print(f" version differs : {len(differ)}")
if args.quiet:
return 0 if not (only_a or only_b or differ) else 1
if only_a:
print(f"\nMISSING on {args.list_b.name} (was on {args.list_a.name}):")
for n in only_a:
print(f" - {n}\t{a[n]['ver']}")
if only_b:
print(f"\nNEW on {args.list_b.name} (not on {args.list_a.name}):")
for n in only_b:
print(f" + {n}\t{b[n]['ver']}")
if differ:
print("\nVERSION DRIFT:")
for n in differ:
print(f" ~ {n}\t{a[n]['ver']} -> {b[n]['ver']}")
return 0 if not (only_a or only_b or differ) else 1
if __name__ == "__main__":
sys.exit(main())Run it
Two input files, one command. This is the real captured output, from the same sandbox session that ran the script above. The demo lists are synthetic: a real capture from an Ubuntu 26.04 box, hand-aged to look like the old staging server.
python3 pkgdiff.py old-server.txt new-server.txt
pkgdiff: old-server.txt (20 pkgs) vs new-server.txt (19 pkgs)
only in old-server.txt: 2
only in new-server.txt: 1
version differs : 7
MISSING on new-server.txt (was on old-server.txt):
- apache2 1:2.4.66-1ubuntu4
- python3-pip 25.1.1+dfsg-1ubuntu2
NEW on new-server.txt (not on old-server.txt):
+ nginx 1.28.3-2ubuntu1.14
VERSION DRIFT:
~ curl 8.12.1-1ubuntu2.4 -> 8.18.0-1ubuntu2.8
~ docker.io 28.3.0-0ubuntu2 -> 29.1.3-0ubuntu4.1
~ git 1:2.50.1-1ubuntu1 -> 1:2.53.0-1ubuntu1.1
~ linux-generic 6.14.0-36.36 -> 7.0.0-43.43
~ openssh-server 1:9.9p1-3ubuntu3.2 -> 1:10.2p1-2ubuntu3.8
~ openssl 3.4.1-1ubuntu4.5 -> 3.5.5-1ubuntu3.7
~ python3 3.13.7-1ubuntu2 -> 3.14.3-0ubuntu2
The MISSING block is the punchline of a migration audit: an old box running Apache became an nginx box, so apache2 falling off is expected, but python3-pip silently disappearing is the kind of thing that bites you two weeks later. It pairs well with the other CSV reconciliation and backup verification scripts on this blog – same idea, different inputs.
The crash that shaped the parser
A genuine catch from verification: my first capture piped dpkg-query -W nginx-core nginx on a box where nginx-core was not installed, and dpkg happily printed a line with an empty version field. The draft parser unpacked that line into a dict and died later on the version lookup. The len(parts) != 3 or not parts[2] guard now fails loudly with file and line number instead of a traceback 200 lines downstream:
python3 pkgdiff.py bad.txt new-server.txt
bad.txt:1: bad line (need name/arch/version, tab-separated): 'broken-meta\tall'Cron it
Store a known-good baseline, run the comparison against a fresh capture, and only act on a non-zero exit:
# nightly drift check, only alert when something moved
python3 /opt/scripts/pkgdiff.py /srv/pkglists/old-server.txt /srv/pkglists/new-server.txt -q || \
curl -fsS --data "drift detected on $(hostname)" https://api.example.net/notifyThree lists, one command, zero surprises left on the table between the old box and the new one.