Skip to content

Pushing configuration changes safely with Netmiko

The Python article called Netmiko "the most common starting point" for network automation, and turning CLI output into structured data used it to read from devices. This article picks up the riskier half — pushing configuration — and the discipline you have to add yourself, because Netmiko drives the raw CLI and gives you none of the safety rails that NAPALM's candidate workflow or Ansible's resource modules do.

The basic change

ConnectHandler opens an SSH session; send_config_set enters configuration mode, sends every command in the list, and exits again. save_config writes the running config to startup (write memory on IOS / IOS XE). The device_type tells Netmiko which CLI dialect to expect — use cisco_ios or cisco_xe for IOS XE.

import os
from netmiko import ConnectHandler

device = {
    "device_type": "cisco_xe",
    "host": "192.0.2.11",
    "username": os.environ["NET_USER"],   # from the environment, never hard-coded
    "password": os.environ["NET_PASS"],
}

vlan_cfg = [
    "vlan 10", "name SALES",
    "interface GigabitEthernet3",
    "switchport mode access",
    "switchport access vlan 10",
]

with ConnectHandler(**device) as conn:
    output = conn.send_config_set(vlan_cfg)
    conn.save_config()                    # persist 'write memory'
    print(output)

Used as a context manager, ConnectHandler guarantees the session is closed even if something raises mid-change. That much is easy. The rest of this article is about the three things Netmiko won't do for you.

Netmiko won't tell you a command failed

send_config_set returns the device's output as one string and, by default, raises nothing when a command is rejected. A fat-fingered line produces % Invalid input detected at '^' marker — and that text lands silently in the returned string while the rest of your commands keep going. The call looks like it succeeded.

The fix is the error_pattern argument: a regex Netmiko checks against the output after each command, raising ConfigInvalidException on a match so a bad line stops the run instead of hiding in a log.

from netmiko.exceptions import ConfigInvalidException

with ConnectHandler(**device) as conn:
    try:
        conn.send_config_set(
            vlan_cfg,
            error_pattern=r"% (Invalid|Incomplete|Ambiguous)",
        )
        conn.save_config()
    except ConfigInvalidException as exc:
        print(f"device rejected a command, nothing saved: {exc}")

There is a sharp edge here that the candidate-based tools don't have: Netmiko applies commands line by line, so a command rejected halfway through leaves the lines before it already on the running config. There is no candidate datastore and no transaction — the device is in a partial state, and it is on you to decide whether to roll it back. Not calling save_config only means the partial change isn't persisted to startup; it is still live. This is exactly the transactional safety that NETCONF's candidate/commit and NAPALM exist to provide.

Mind the read timeout

Netmiko 4.x replaced the old delay_factor timing model with a per-operation read_timeout, which defaults to 15 seconds. Most config lines return instantly, but some don't — writing a large ACL, copying a file, generating a crypto key, or saving a big config can all run long. When the device is still working and Netmiko stops reading, you get a ReadTimeout on a change that was actually fine.

Raise the timeout on calls you know are slow rather than globally:

conn.send_config_set(big_acl, read_timeout=120)
conn.save_config(read_timeout=60)

Netmiko is not idempotent — you are

A resource module or a Terraform apply converges a device to a declared end state, so running it twice changes nothing the second time. Netmiko does no such thing: it sends exactly the lines you hand it, every time. Re-running a script that adds an ACL entry adds it again; a script that appends to a route-map appends again. Netmiko has no idea what "already done" means.

That makes idempotency your job. Three ways to get it:

  • Render the full intended stanza from a source of truth with Jinja2 and push that, so the config is declarative even though the transport isn't.
  • Check before you change — read the current state (with use_textfsm=True for structured output), compare it to what you want, and only send the delta.
  • Reach for a declarative tool when the config is stateful and the safety matters more than the flexibility. Netmiko shines for CLI that no resource module or YANG model covers yet; it is the wrong tool for config you need to converge repeatedly.

Make every change auditable

Two small habits turn an ad-hoc script into something you can trust in production. session_log captures the full SSH transcript — every command and every response — which is the record you want when a change is questioned later. And send_config_from_file keeps the config you pushed in a reviewable, version-controlled file instead of a Python list.

device["session_log"] = f"{device['host']}.log"

with ConnectHandler(**device) as conn:
    conn.send_config_from_file("interfaces.cfg",
                               error_pattern=r"% (Invalid|Incomplete|Ambiguous)")
    conn.save_config()

A safe-change template

Putting it together with the robust-code habits from the rest of the site — credentials from the environment, every failure caught, nothing saved until the change is clean:

import os
from netmiko import ConnectHandler
from netmiko.exceptions import (
    NetmikoTimeoutException,
    NetmikoAuthenticationException,
    ConfigInvalidException,
)

device = {
    "device_type": "cisco_xe",
    "host": "192.0.2.11",
    "username": os.environ["NET_USER"],
    "password": os.environ["NET_PASS"],
    "session_log": "change.log",
}

try:
    with ConnectHandler(**device) as conn:
        conn.send_config_set(
            config_commands,
            read_timeout=60,
            error_pattern=r"% (Invalid|Incomplete|Ambiguous)",
        )
        conn.save_config()
except ConfigInvalidException:
    print("device rejected a command — review change.log; config may be partial")
except NetmikoAuthenticationException:
    print("authentication failed — check credentials")
except NetmikoTimeoutException:
    print("device unreachable or too slow to respond")

Then prove it on a canary before you fan it out. When you push changes across a fleet with concurrency, remember that Netmiko's lack of a transaction means a bad change hits every worker's device for real — validate on one box first, roll out in batches, and confirm each batch with pyATS before moving on.

Key takeaways

  • send_config_set enters config mode, sends your lines, and exits; save_config persists them. Used as a context manager, ConnectHandler always closes the session.
  • By default Netmiko does not flag a rejected command — the error text just appears in the returned string. Pass error_pattern so a bad line raises ConfigInvalidException and stops the run.
  • There is no candidate datastore. Commands apply line by line, so a mid-run failure leaves a partial change live on the device; use NETCONF/NAPALM when you need an all-or-nothing commit.
  • read_timeout (default 15s) is per-operation in Netmiko 4.x — raise it for slow commands so a long-running change doesn't look like a timeout.
  • Netmiko is not idempotent. It sends exactly what you give it every time, so build idempotency in yourself: render from a source of truth, diff-before-change, or use a declarative tool.
  • Log every change with session_log, keep pushed config in version-controlled files, read credentials from the environment, and canary-then-batch before touching the fleet.

Sources: Netmiko on GitHub, Netmiko send_config_set source, Netmiko exceptions, Netmiko timing / read_timeout notes.