New batchNext CCNA batch starts Friday 15 August · Morning 7:30 – 9:30 AMBook a free demo →
Networking Tutorials

Netmiko Tutorial: Automating Cisco Devices with Python

Netmiko is a Python library that automates SSH connections to network devices. It handles the awkward parts of screen-scraping a CLI — logging in, entering enable mode, dealing with paging and prompts — so you can focus on the commands. It is the single most practical entry point into network automation, because it works with the Cisco devices you already have.

Why Netmiko exists

Suppose you need to check the IOS version on 200 switches. You could SSH into each one, type show version, and copy the output. That is a full day of tedious, error-prone work — and you will have to do it again next month.

You could use raw Python with the paramiko SSH library, but you would immediately hit the reality of automating a CLI that was designed for humans:

  • The device pages output with --More-- and waits for a keypress.
  • The prompt changes as you move between modes (>, #, (config)#).
  • You must detect when a command has finished, which means pattern-matching the prompt.
  • Every vendor does all of this slightly differently.

Netmiko wraps paramiko and solves every one of those problems. It knows the prompt patterns for dozens of platforms, disables paging automatically, and gives you a clean, readable API. It is the difference between fighting the CLI and using it.

Installation and first connection

Install it:

pip install netmiko

Now connect to a switch and run a command:

from netmiko import ConnectHandler

device = {
    "device_type": "cisco_ios",
    "host": "192.168.1.10",
    "username": "admin",
    "password": "YourPassword",
    "secret": "YourEnableSecret",   # for enable mode
}

conn = ConnectHandler(**device)
conn.enable()                       # enter privileged EXEC

output = conn.send_command("show ip interface brief")
print(output)

conn.disconnect()

That is genuinely the whole thing. Netmiko logged in, entered enable mode, turned off paging, ran the command, waited for the prompt to return, and handed you the output as a string.

The device_type is the key setting. Common values: cisco_ios, cisco_xe, cisco_nxos, cisco_asa, arista_eos, juniper_junos. Netmiko supports well over 100 platforms.

Never hardcode passwords in a script you will commit to Git. Use environment variables or a secrets manager. This is a habit to build from day one, not later.

Pushing configuration

Reading is useful. Configuring is where the real time is saved. Use send_config_set() — Netmiko enters config mode, sends each line, and exits for you.

config = [
    "interface GigabitEthernet0/2",
    "description Uplink to Core",
    "switchport mode access",
    "switchport access vlan 20",
    "no shutdown",
]

output = conn.send_config_set(config)
print(output)

conn.save_config()   # writes running-config to startup-config

Notice you do not write configure terminal or end — Netmiko handles the mode transitions. You just supply the commands.

save_config() runs the platform-appropriate save command (write memory on IOS). Forgetting it is the classic beginner mistake: your change works perfectly until the device reboots and reverts.

Automating across many devices

This is the payoff. Loop over a device list and the 200-switch job takes ninety seconds.

from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoTimeoutException, NetmikoAuthenticationException
import os

switches = ["192.168.1.10", "192.168.1.11", "192.168.1.12"]

for ip in switches:
    device = {
        "device_type": "cisco_ios",
        "host": ip,
        "username": os.environ["NET_USER"],
        "password": os.environ["NET_PASS"],
    }
    try:
        with ConnectHandler(**device) as conn:
            ver = conn.send_command("show version | include Version")
            print(f"{ip}: {ver.strip()}")
    except NetmikoAuthenticationException:
        print(f"{ip}: AUTH FAILED")
    except NetmikoTimeoutException:
        print(f"{ip}: UNREACHABLE")

Three things here are worth internalising, because they separate a script that works once from one you can trust:

  • Use with. It guarantees the connection is closed even if something throws. Leaked SSH sessions eventually exhaust the device's VTY lines and lock you out.
  • Catch exceptions per device. One unreachable switch must not kill the run. Handle the failure, log it, and carry on.
  • Read credentials from the environment. Not from the source file.

Structured output with TextFSM

send_command() returns a wall of text. Parsing it with string operations and regex is fragile — the output format changes between IOS versions and your script silently breaks.

Netmiko integrates with TextFSM, which parses CLI output into structured Python data using community-maintained templates:

result = conn.send_command("show ip interface brief", use_textfsm=True)

for iface in result:
    if iface["status"] == "up":
        print(iface["interface"], iface["ip_address"])

Now result is a list of dictionaries rather than a blob of text. You can filter it, count it, write it to CSV, feed it into a report. This one flag is the difference between a brittle script and a maintainable tool.

Install the templates with pip install ntc-templates.

Where Netmiko fits — and where it does not

Be clear-eyed about this, because it is a common source of confusion.

ToolUse it when
NetmikoYou need scripted CLI access to devices you already have. Ad-hoc automation, audits, bulk changes, custom tooling.
AnsibleYou want declarative, idempotent config management with inventory and playbooks, and less Python.
NETCONF / RESTCONFThe devices support proper APIs. Structured data, no screen-scraping, far more robust.

Netmiko is screen-scraping. It is automating a human interface, and that is inherently less robust than a real API. In a greenfield network with modern devices, NETCONF/RESTCONF is the better answer.

But most real networks are not greenfield. They contain equipment that is ten years old and will never speak NETCONF, and Netmiko works on all of it. That pragmatism is exactly why it remains the most widely used network-automation library in the world — and why learning it is one of the highest-return investments a network engineer can make. Start with our Python for network engineers guide, and see the automation engineer career path for where this leads.

Frequently asked questions

What is Netmiko used for?

Netmiko is a Python library that automates SSH connections to network devices. It handles login, enable mode, paging and prompt detection, so you can run commands and push configuration across many devices programmatically.

Is Netmiko better than Ansible?

They serve different purposes. Netmiko gives you full programmatic control in Python and is ideal for custom tooling and ad-hoc automation. Ansible is better for declarative, idempotent configuration management with less code.

Does Netmiko work with non-Cisco devices?

Yes. It supports over 100 platforms including Arista EOS, Juniper Junos, HP, Palo Alto and F5. You select the platform with the device_type setting.

What is use_textfsm in Netmiko?

A flag on send_command that parses raw CLI output into structured Python dictionaries using TextFSM templates, instead of returning a block of text. It makes scripts far more reliable across IOS versions.

Do I need to know Python well to use Netmiko?

No. Basic Python — variables, loops, lists and dictionaries — is enough to be productive. Netmiko is deliberately designed so that a working script is only a few lines long.

VS
Vipul Sir — Lead Instructor, Attila Technologies20+ years in Cisco networking. Teaching CCNA, CCNP, CCIE & CyberOps in Ahmedabad since 2004.

Want hands-on training?

Learn this on real Cisco lab devices with placement support at Attila Technologies, Ahmedabad.

Start your networking career with Attila Technologies

Hands-on Cisco training, real lab devices and placement support in Ahmedabad.