Use Scrapli as an observation tool before you use it for configuration
Scrapli is a Python library for communicating with network equipment, usually over an interactive command-line transport such as SSH. Its main value in network-state analysis is repeatable command execution with structured responses: instead of visiting ten routers manually and forgetting which commands were run, an engineer can collect the same observable state from a defined device inventory. Automation does not make the underlying device data correct; it makes acquisition repeatable enough to validate and compare. A network automation task aligned with Cisco 300-435 ENAUTO should record command failures and compare parsed device state with expected values before reporting that a change succeeded.
A safe workflow begins with a scoped inventory, read-only credentials where the platform supports them, encrypted authentication, and clearly defined commands. Avoid placing passwords, private keys, production addresses, or device transcripts containing secrets in published scripts or logs. A shared automation account with unrestricted privileges across every network platform is not an acceptable shortcut.
Establish connectivity and identify the exact platform
A script should know which device family it is interacting with. Cisco IOS XE, Junos, IOS XR, and NX-OS may use different commands, prompts, and privilege modes. Choose the supported driver for the target system or use a generic driver with explicit prompt and platform handling. Confirm the required transport and access permissions, and validate server identity rather than suppressing SSH host-key checking to make a demonstration easier.
The following minimal example is intentionally read-only. It uses the Cisco IOS XE driver on a test router and an environment variable for the authentication secret. Run it only against a device you are authorized to inspect, with a properly configured SSH trust store and current driver documentation.
import os
from scrapli.driver.core import IOSXEDriver
router = {
"host": "192.0.2.10", # Documentation-only example address
"auth_username": os.environ["NET_USERNAME"],
"auth_password": os.environ["NET_PASSWORD"],
"auth_strict_key": True,
}
with IOSXEDriver(**router) as connection:
response = connection.send_command("show ip interface brief")
if response.failed:
raise RuntimeError("Interface-state collection failed")
print(response.result)
Never silently retry every failed command with elevated privilege. If a connection fails, classify whether the problem is reachability, SSH negotiation, host-key trust, credentials, role permissions, or prompt detection before changing anything.
Collect observations that answer a specific operational question
“Gather network state” is too broad to be an actionable task. Instead, define one answerable question: which interfaces were administratively down between two inventory snapshots; which BGP peers have changed state; whether a selected VLAN is present on an uplink; or which route to a prefix is currently active. Collect the smallest command set needed to answer it.
For interface inventory, record hostname, software family, command timestamp, interface identifier, operational state, and the exact raw response or a fingerprint of it. Compare subsequent snapshots by stable keys rather than line number or column position: network device output formatting may change between releases. A missing row should not be interpreted automatically as a deleted physical port; it may indicate collection failure or renamed interface syntax.
For a VLAN-change review, distinguish the configured VLAN definition, membership on the relevant trunk, MAC learning, and real Layer 3 reachability. A VLAN fundamentals primer helps explain why those observations cannot be reduced to a single command result.
Convert raw command text into trustworthy structured records. Raw CLI output is not a stable data contract. For high-confidence automation, use structured APIs or device-native JSON/XML outputs when the platform supports them. If you must parse text, specify the software version and parser, test normal and error cases, and record parse failures separately from genuine device faults. A show command that returns a privilege error is not an empty network state.
Scrapli responses include the returned result and failure indication, but they are not a guarantee that a device’s response is semantically valid for the intended question. Implement checks for truncation, timeouts, pager artifacts, locale or terminal settings, and command-specific error tokens. Store raw evidence with an appropriate retention policy so a false alert can be traced back to the original observation.
Handle concurrency and device load carefully
Collecting from a fleet introduces additional engineering choices. Limit concurrent SSH sessions according to device capability, management-plane rate limits, and change-window restrictions. Timeouts should be per connection and per command where the library supports them; an aggressive timeout that works on a lab router may systematically misclassify busy production devices as down.
Use an explicit inventory that names permitted targets, define a bounded retry policy, and separate connectivity failures from data-validation failures in the result schema. Provide enough timestamps and software identity information to distinguish two snapshots taken around a routing convergence event.
For asynchronous workflows, use the supported async driver and transport documented for the platform; do not mix synchronous object lifecycle calls into an event loop or assume any synchronous library can be made safe merely by prepending await. If you use Nornir with Scrapli, verify that task outputs preserve device identity and raw response provenance.
Make state comparisons auditable
A useful comparison record includes the device, data point, previous observation, current observation, observation times, and whether the collection was trustworthy. For routing, compare the chosen prefix, next hop, route source, and routing table separately. For an interface, compare administrative state, operational state, errors, and link speed. Use thresholding, debouncing, and incident correlation to avoid flooding operators with transient changes that do not affect service.
Security and privacy apply to collected data too: configuration snapshots may include credentials or sensitive network topology. Protect the inventory, apply role-based permissions, and redact secrets before writing diagnostics. Do not commit production running configurations or authentication debug logs to a public source repository.
Separate measurement automation from configuration automation
Executing read-only commands is lower risk than changing a device. Before automating changes, require source-of-truth verification, review of intended deltas, a maintenance window, staged rollout, commit check or equivalent validation, a suitable rollback plan, and post-change service tests. Device-specific transaction and checkpoint capabilities vary. A command that succeeded does not prove that the intended traffic path or security posture is correct.
Treat the output of a single Scrapli command as evidence, not as an autonomous decision to change production configurations. The safest first deployment is a limited-scope inventory and state-observation job, with clear error reporting and human review.
A hands-on skill plan. Begin with one lab device and two approved show commands. Verify SSH trust, collect raw responses, then parse the minimum useful fields. Add a second device of the same platform and compare. Introduce a simulated failure so that the script must distinguish a real state change from transport and parsing errors. Finally test a topology containing two supported device families and document the driver differences.
The finished result should answer a real engineering question with verifiable evidence. If it only prints a lengthy console transcript, you have automated data collection but not yet created useful network-state analysis. Scrapli supplies the transport and device interaction framework; the engineer remains responsible for data quality, security, interpretation, and operational decisions.
Response handling and false-success testing
A command automation job should treat three events differently: the command ran and produced valid data, the command ran but returned a device error, and the command was not executed because transport or authentication failed. Build a test harness that exercises all three. For example, request a valid read-only interface command, send a deliberately unsupported command on a lab device, and simulate a closed TCP port. The summary should identify each outcome separately rather than reporting an empty result in all cases.
When a parser sees an unexpected software version or format, retain the sanitized original output and mark the parsed fields uncertain. Avoid comparing a stale prior snapshot to a failed current collection and claiming the device went down. The validity of your diff is limited by the validity of both snapshots.
Secure operational rollout
Before expanding beyond one lab router, define a concurrency cap, SSH known-hosts management, short-lived credentials, target allowlists, a collection timeout, retention rules, and a rule for escalating repeated failures. Test against a device deliberately under management-plane load to identify timeout tuning needs. If a platform requires privilege elevation, decide whether this is appropriate at all for a purely observational task.
For multivendor automation, do not rename every output field to a generic concept without confirming its meaning. An interface reported as up may refer to administrative, protocol, or physical carrier state depending on the command and device. Record normalization assumptions in the data model so an engineer can explain exactly which signal triggered an alert.
Test failure handling, not only successful collection
Scrapli sessions should have bounded timeouts and explicit exception handling. A transport failure, invalid authentication, unexpected prompt or partially returned command output must not be written to a report as if it were a valid device state. Build a test that intentionally returns an empty route table and another that fails halfway through command collection. Verify that the report distinguishes these outcomes from a healthy device with no matching routes. When collection runs concurrently, cap the number of sessions so lab success does not translate into uncontrolled load on production control planes. Record software platform, collection timestamp, command, parsing status and the device identity for each observation.