Free tech learning for everyone, from basics to pro

Network AutomationProgramming and Application SecurityIntermediate

Network configuration compliance and drift detection with Python

In short: Configuration drift is any difference between how a device should be configured and how it actually is. Compliance checks compare live configuration with golden rules or a full intended configuration. Python can collect configs, test rules, produce diffs and report results on a schedule.

What drift is and why it matters

Drift happens when a device’s running configuration moves away from its intended state: an emergency fix that was never documented, a test ACL left behind, a password policy missed on a new switch. Each one is small, but together they create security gaps and make troubleshooting harder. Compliance checking compares devices against agreed standards and reports what does not match. It supports audits for frameworks such as ISO/IEC 27001:2022 and PCI DSS, and hardening guides such as the CIS Benchmarks.

Compliance loopDefinegolden rulesCollectlive configsComparerules and diffsReportpass or failRemediatefix or approve
Figure 1. Compliance is a repeating loop, not a one-off audit.

Two ways to check

Two kinds of checkRule-basedMust or must-not linesEasy to explainMaps to CIS benchmarksIgnores unrelated configFull diffIntended vs runningCatches any changeNeeds a complete intentNoisier at first
Figure 2. Rule checks test specific requirements; full diffs catch any difference from intended state.

Most teams start with rule-based checks because they are easy to agree on, then move towards full intended-configuration diffs as their source of truth matures.

Rule checks in Python

This script reads saved running configurations (collected earlier with Netmiko or NAPALM) and tests required and forbidden lines. It is read-only, so it is safe to run as often as you like.

import re
from pathlib import Path

REQUIRED = [
    r"^service password-encryption$",
    r"^ip ssh version 2$",
    r"^logging host \S+",
    r"^ntp server \S+",
]
FORBIDDEN = [
    r"^ip http server$",
    r"^snmp-server community public",
    r"^\s*transport input .*telnet",
]

for cfg_file in sorted(Path("backups").glob("*.cfg")):
    text = cfg_file.read_text(encoding="utf-8")
    missing = [p for p in REQUIRED if not re.search(p, text, re.M)]
    present = [p for p in FORBIDDEN if re.search(p, text, re.M)]
    status = "PASS" if not (missing or present) else "FAIL"
    print(f"{cfg_file.stem}: {status}")
    for p in missing:
        print("   missing:", p)
    for p in present:
        print("   forbidden:", p)

Diffs against intended configuration

When you can render the full intended configuration (for example from Jinja2 and NetBox), compare it line by line with the running one. The standard library difflib produces a readable unified diff.

import difflib
from pathlib import Path

intended = Path("intended/acc-sw1.cfg").read_text(encoding="utf-8").splitlines()
running = Path("backups/acc-sw1.cfg").read_text(encoding="utf-8").splitlines()

IGNORE = ("!", "Building configuration", "Current configuration", "ntp clock-period")
running = [l for l in running if not l.startswith(IGNORE)]
intended = [l for l in intended if not l.startswith(IGNORE)]

diff = list(difflib.unified_diff(intended, running, "intended", "running", lineterm=""))
print("\n".join(diff) if diff else "No drift")

Tip: filter out lines that change on their own, such as timestamps and counters, or every run will report false drift and people will stop reading the reports.

Other tools can do the heavy lifting: NAPALM’s compare_config() with a replace candidate, Ansible’s check mode with diff, or the open-source Batfish, which analyses configurations offline to answer questions such as "can this subnet reach that server?".

Remediation and reporting

  1. Back up running configurations on a schedule and keep them in Git, so you can see when drift appeared.
  2. Run checks after every change window and at least daily.
  3. Send a summary to the team or a ticket queue; send failures for critical rules as alerts.
  4. For each finding, decide: fix the device, or update the standard if the change was valid.
  5. Automate fixes only for low-risk, well-tested rules, and keep a human approval step for the rest.

Treat backups and reports as sensitive: configurations contain password hashes, SNMP (Simple Network Management Protocol) strings and network layout. Store them with restricted access and strip or mask secrets in reports.

Practice

What is configuration drift?
Any difference between a device’s intended configuration and its actual running configuration.
Why filter timestamp lines before diffing configurations?
They change on every collection, so leaving them in creates false drift reports that hide real problems.
A rule check finds an undocumented ACL that was added during an outage. What are your two options?
Remove it and restore the standard, or, if the change was correct, update the standard and source of truth through change control so it becomes intended state.

Key takeaways

  • Drift is the gap between intended and running configuration.
  • Rule checks test required and forbidden lines; diffs catch every change.
  • Python re, pathlib and difflib are enough for a first compliance tool.
  • Filter noisy lines and run checks on a schedule.
  • Keep backups in Git, protect them, and approve fixes through change control.
Tracks your learning on this device only. See your progress on the learning paths.

About the author

Mohamed Fayas

Founder of FM TecHub. CCNA certified, with a BTEC HND in Network Engineering, and BEng (Hons) in Computer Networking and Cloud Security. He writes practical, plain-English guides on networking, security and cloud.

More about the author

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Stay up to date by email

New notes, tools and security news from FM TecHub, explained simply. Free.

We only use your email to send these updates. See our privacy policy.