Netmiko Python Script: Configure Cisco IOS Devices - 夜莺博客

Netmiko Python Script: Configure Cisco IOS Devices

Ansible is the right tool for repeatable, declared changes, but there is a category of work where a plain Python script wins: one-off mass show collections, ad-hoc remediation across a list of hosts, or a custom workflow that does not fit a module. Netmiko is the library that makes those scripts short, and its API answers most questions in about twenty lines.

Install and connect

pip install netmiko

from netmiko import ConnectHandler
from getpass import getpass

cisco1 = {
    "device_type": "cisco_ios",
    "host": "10.0.0.1",
    "username": "netadmin",
    "password": getpass(),
    "secret": getpass(prompt="enable: "),
}

with ConnectHandler(**cisco1) as conn:
    print(conn.find_prompt())
    conn.enable()

Use the context manager so the SSH session is closed even when an exception is raised mid-script. device_type selects the right platform behaviour — cisco_ios, cisco_xr, cisco_nxos, juniper_junos, arista_eos — and a wrong value produces plausible-looking output with broken parsing.

Read: send_command

out = conn.send_command("show interfaces status", use_textfsm=True)
for row in out:
    if row["status"] == "notconnect":
        print(row["interface"])

use_textfsm=True pipes the raw output through a TextFSM template and returns structured records, which removes the regex-per-platform tax that makes multi-vendor scripting painful. If a template is missing for your platform, the raw string is returned instead — always check the type before iterating.

Write: send_config_set, then commit or save

cmds = ["vlan 30", "name server_vlan", "interface Gi1/0/1",
        "switchport mode access", "switchport access vlan 30"]
out = conn.send_config_set(cmds)
print(out)

# IOS / IOS-XE / NX-OS
conn.save_config()
# IOS XR, Junos, PAN-OS use an explicit commit instead:
# conn.commit()

This is the single most common mistake in hand-written scripts: calling commit() on a platform that has no commit, or forgetting save_config() on IOS and losing the change at the next reload. Match the call to the platform.

Bulk runs and safety habits

import logging
logging.basicConfig(filename="netmiko.log", level=logging.INFO)
logging.getLogger("netmiko").setLevel(logging.DEBUG)

for host in hosts:
    try:
        with ConnectHandler(device_type="cisco_ios", host=host,
                            username=user, password=pw) as conn:
            print(host, conn.send_command("show version | include uptime"))
    except Exception as e:
        print(host, "FAILED", e)

Three habits make scripts safe enough to keep: enable session logging so every command is auditable, wrap each device in its own try/except so one unreachable switch does not abort the run, and always collect a show running-config before pushing anything. For anything scheduled and repeatable, graduate the script into an Ansible playbook so the change process, not the script, owns the logic.

Related reading: NTC templates and TextFSM parsing, Ansible Cisco network automation 101, Juniper PyEZ and NETCONF automation.

原文链接:Netmiko EXAMPLES.md