Netmiko Python Automation for Network Engineers: Getting Started - 夜莺博客

Netmiko Python Automation for Network Engineers: Getting Started

Netmiko is the Python library that makes network automation approachable: it wraps SSH sessions to network devices and gives you simple methods like send_command() and send_config_set(), handling all the vendor quirks (prompts, pagination, privilege levels) under the hood. Created by Kirk Byers, it supports 60+ platforms including Cisco IOS/IOS-XR/NX-OS, Juniper Junos, Arista EOS, Huawei VRP and Aruba. This article shows you how to install it, connect to a device, run commands, push configuration, and write a practical config-backup script you can run every night.

Installation

pip install netmiko

Netmiko needs Python 3.7+ and uses Paramiko for SSH. Optional extras: pip install netmiko[textfsm] enables structured output parsing.

First Connection and Command Execution

from netmiko import ConnectHandler

device = {
    "device_type": "cisco_ios",
    "host": "192.168.1.10",
    "username": "admin",
    "password": "secret",
    "port": 22,
}

with ConnectHandler(**device) as conn:
    output = conn.send_command("show ip interface brief")
    print(output)

device_type is the most important field - pick from values like cisco_ios, cisco_xr, juniper_junos, arista_eos, huawei, dell_os10, linux. Using with closes the connection automatically.

Pushing Configuration

config_commands = [
    "interface GigabitEthernet0/1",
    "description Uplink-to-core",
    "switchport mode trunk",
    "switchport trunk allowed vlan 10,20",
]
with ConnectHandler(**device) as conn:
    conn.send_config_set(config_commands)
    conn.save_config()  # write memory / copy running-config startup-config

send_config_set() enters config mode, sends each line, and exits. save_config() knows the vendor-specific save command.

Practical Script: Nightly Config Backup

import datetime
from netmiko import ConnectHandler

devices = [
    {"device_type": "cisco_ios", "host": "192.168.1.10", "username": "admin", "password": "secret"},
    {"device_type": "juniper_junos", "host": "192.168.1.11", "username": "admin", "password": "secret"},
    {"device_type": "arista_eos", "host": "192.168.1.12", "username": "admin", "password": "secret"},
]

for dev in devices:
    try:
        with ConnectHandler(**dev) as conn:
            config = conn.send_command("show running-config")
            date = datetime.date.today().isoformat()
            filename = f"backup/{dev['host']}_{date}.cfg"
            with open(filename, "w") as f:
                f.write(config)
            print(f"Backed up {dev['host']} -> {filename}")
    except Exception as e:
        print(f"FAILED {dev['host']}: {e}")

Add a cron job and you have automated config backup across a multi-vendor fleet in under 30 lines.

Structured Output with TextFSM

output = conn.send_command("show ip interface brief", use_textfsm=True)
for interface in output:
    print(interface["interface"], interface["ip_address"], interface["status"])

With use_textfsm=True you get a list of dicts instead of raw text - perfect for feeding dashboards or comparing state.

Error Handling and Best Practices

  • Wrap connections in try/except and log failures - one dead device should not stop the whole batch.
  • Store credentials in environment variables or a secrets manager, never in the script.
  • Use conn.enable() explicitly when the device needs privileged mode (or set secret in the dict).
  • For device_type discovery use netmiko.ssh_dispatcher.class_mapper() or the device_type autodetect in newer versions.

Going Further

Netmiko pairs naturally with Ansible (network modules), Nornir (parallel execution) and TextFSM/ntc-templates. For inventory and parallelism, Nornir + Netmiko is the power combo used by many network teams.

Related: Ansible network automation and multi-vendor automation with Ansible and Jinja2.

原文链接:https://github.com/ktbyers/netmiko