4 Network Automation with Python
Learn how to build Python network automation that validates inputs, plans and applies controlled changes, verifies device state, and handles failures safely.
Principles of network automation
Effective network automation does more than send commands quickly. It collects device state, compares it with intended state, makes controlled changes, and verifies the result so that changes are predictable, reviewable, and recoverable.
A useful script separates data, logic, and device access. Keep inventories and desired values in , put reusable operations in functions, and use a network library or API client to communicate with devices.
Python building blocks and input validation
Python provides the basic constructs used to organize automation:
Variables and collections: Lists can hold groups of devices; dictionaries can hold attributes such as hostname, platform, and management address.
Conditionals:
ifstatements select actions based on results, such as whether a device needs a change.Loops:
forstatements apply the same procedure to each device in an inventory.Functions: Named, reusable units make scripts easier to test and maintain.
Exceptions:
tryandexceptblocks handle expected failures, such as a connection timeout, without hiding unrelated errors. Catch specific exceptions where practical.
Validate management addresses before attempting connections. The standard-library ipaddress module parses IPv4 and IPv6 addresses and raises an error for invalid input.
A controlled configuration workflow
A reliable configuration workflow makes each change deliberate and easier to audit:
Load and validate inputs. Check that the device list, platform, requested values, and required credentials are present.
Connect securely. Use the approved management interface and authenticate with an account intended for automation.
Read current state. Collect the facts, configuration, or operational data needed for the task.
Calculate the change. Compare current state with desired state and avoid changing devices that already comply.
Review before applying. Produce a diff or plan. Use a or explicit approval for consequential changes.
Apply the smallest suitable change. Determine whether the device or library merges or replaces configuration; replacement can affect more than the intended setting.
Verify live state. Check the operational result, not only whether the configuration command succeeded.
Record and clean up. Log successes and failures, preserve useful change records, and close sessions even if an error occurs.
This process is safer to rerun and easier to audit. In larger environments, keep inventory and desired data separate from execution logic, and track scripts and data in version control. Network automation platforms also commonly separate the data model from the modules that perform device operations.
Stage, review, apply, and verify
The following example uses 's common driver interface to stage a change for one device. It reads credentials from environment variables instead of embedding passwords in source code. By default, it displays the proposed diff and discards the candidate; it applies the change only when APPLY=1.
The candidate configuration can be reviewed with compare_config() and then committed or discarded. A device with no diff is already compliant, so the script discards the candidate and makes no change. Support and exact behavior vary by platform and driver; check the target device's capabilities before relying on this workflow.
After a commit, the example retrieves device facts and checks the reported hostname against the intended name. This is : a successful commit alone does not prove that the device is operating as intended.
This example is not a complete production change-control system. For risky changes, use a tested rollback method or a supported commit-confirm/revert timer, capture a backup, and define how the script should respond if verification fails. A failed post-change check calls for investigation and the organization's recovery procedure; it should not be silently treated as success.
Safety, resilience, and maintainability
Automation must account for failures and operational risk as well as the intended configuration:
Handle failures narrowly. Handle known connection or device errors explicitly, log which device failed, and allow unexpected programming errors to remain visible. Close sessions in a
finallyblock or use a library's context-manager support where available.Bound waiting and retries. Set timeouts so an unresponsive device cannot make a script wait indefinitely. Retry only errors likely to be temporary, and do not blindly repeat non- operations.
Make runs . Compare current and desired state rather than issuing commands unconditionally, so a rerun ideally makes no further changes once the desired state is reached.
Protect secrets. Use an approved secrets manager or protected environment injection. Do not commit credentials, tokens, or private keys to source control.
Log useful details. Record device identity, action, outcome, and error context without recording passwords or other sensitive values. Python's
loggingmodule supports configurable loggers and handlers.Test safely. Unit-test parsing and planning functions with sample data. Test device interactions in a lab or simulator, then use a small canary group before broader deployment.
Choose interfaces deliberately. Prefer a device API or vendor-supported library when available, since it generally exposes and explicit operations. CLI automation can still be useful, but command output and prompts may differ between platforms; treat parsing and platform-specific behavior as explicit concerns. Network tooling can also support different connection methods and platform collections.
Together, input validation, state comparison, careful review, minimal changes, live verification, explicit failure handling, protected credentials, and planned recovery make automation safer to operate and maintain.