Recommended

Python Network Automation: Getting Started With Netmiko and NAPALM

Kunal Nagaria

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.

Python for Network Engineers: Using Netmiko and NAPALM

Network engineering has undergone a quiet revolution over the last decade. Gone are the days when logging into devices one by one and typing commands manually was acceptable practice. Today, automation is not a nice-to-have skill — it is a career-defining one. Python has emerged as the go-to language for network professionals, and two libraries in particular have made the journey from CLI warrior to automation engineer dramatically more accessible: Netmiko and NAPALM.

Whether you manage a handful of routers or thousands of switches across multiple data centers, understanding these tools will transform how you work. This post walks you through what each library does, when to use one over the other, and practical examples to get you started.


Why Python for Network Automation?

Python code on a screen automating network devices using Netmiko and NAPALM libraries for network engineers.

Before diving into the libraries themselves, it is worth understanding why Python became the dominant language in network programming.

  • Readable syntax makes it easy for engineers who are not professional developers to pick up quickly
  • Rich ecosystem of networking libraries eliminates the need to build tools from scratch
  • Strong community support means abundant documentation, tutorials, and Stack Overflow answers
  • Cross-platform compatibility allows scripts to run on Linux, macOS, and Windows

Most importantly, Python allows network engineers to stop doing repetitive work. Pushing the same VLAN configuration to 50 switches, auditing ACLs across hundreds of devices, or generating compliance reports — all of these tasks become scriptable, repeatable, and less error-prone.


Understanding Netmiko

What Is Netmiko?

Netmiko is a multi-vendor SSH library built on top of Paramiko, the foundational Python SSH module. Created by Kirk Byers, Netmiko was specifically designed to handle the quirks that come with connecting to network devices — things that general-purpose SSH libraries were never built to handle, such as:

  • Detecting and interacting with CLI prompts
  • Handling enable mode on Cisco devices
  • Managing timing issues and buffering during long command outputs
  • Supporting a massive variety of vendors including Cisco IOS, Juniper, Arista, Palo Alto, and many more

Installing Netmiko

Getting started is straightforward:

pip install netmiko

A Basic Netmiko Connection

Here is a simple example connecting to a Cisco IOS device and retrieving interface information:

from netmiko import ConnectHandler

device = {
    "device_type": "cisco_ios",
    "host": "192.168.1.1",
    "username": "admin",
    "password": "secretpassword",
    "secret": "enablepassword",
}

connection = ConnectHandler(device)
connection.enable()

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

connection.disconnect()

The send_command method handles prompt detection automatically, so you do not need to worry about timing or buffer management. Netmiko takes care of that complexity behind the scenes.

Sending Configuration Commands

Netmiko makes it equally simple to push configuration changes. The send_config_set method accepts a list of commands:

from netmiko import ConnectHandler

device = {
    "device_type": "cisco_ios",
    "host": "192.168.1.1",
    "username": "admin",
    "password": "secretpassword",
    "secret": "enablepassword",
}

config_commands = [
    "interface GigabitEthernet0/1",
    "description Uplink to Core",
    "ip address 10.0.0.1 255.255.255.252",
    "no shutdown",
]

with ConnectHandler(device) as conn:
    conn.enable()
    output = conn.send_config_set(config_commands)
    conn.save_config()
    print(output)

Using the with statement ensures the connection is properly closed even if an error occurs — a best practice worth adopting from the start.

When to Use Netmiko

Netmiko is your best friend when you need:

  • Granular control over CLI interactions
  • Support for legacy devices that lack APIs
  • Screen scraping — parsing text output from show commands
  • Quick, targeted automation without a lot of abstraction

Understanding NAPALM

What Is NAPALM?

NAPALM stands for Network Automation and Programmability Abstraction Layer with Multivendor support. While Netmiko connects to devices and sends raw commands, NAPALM takes a higher-level approach. It provides a unified API that abstracts vendor-specific differences, so your Python code looks the same whether you are talking to a Cisco IOS router, a Juniper device, or an Arista switch.

NAPALM communicates with devices using a variety of underlying protocols depending on the vendor — SSH, NETCONF, eAPI, and others — and returns structured data instead of raw text strings.

Installing NAPALM

pip install napalm

Connecting and Retrieving Structured Data

Here is where NAPALM shines. Instead of parsing raw text output, you get clean Python dictionaries:

import napalm

driver = napalm.get_network_driver("ios")

device = driver(
    hostname="192.168.1.1",
    username="admin",
    password="secretpassword",
    optional_args={"secret": "enablepassword"},
)

device.open()

Get structured interface information

interfaces = device.get_interfaces() for name, details in interfaces.items(): print(f"Interface: {name}") print(f" Enabled: {details['is_enabled']}") print(f" Speed: {details['speed']} Mbps") print() device.close()

Compare this with Netmiko, where you would receive a block of text from show interfaces and need to write regular expressions or use TextFSM to extract the same data. NAPALM eliminates that parsing work entirely.

Configuration Management with NAPALM

NAPALM includes powerful configuration management capabilities with built-in diff and rollback support:

import napalm

driver = napalm.get_network_driver("ios")

device = driver(
    hostname="192.168.1.1",
    username="admin",
    password="secretpassword",
    optional_args={"secret": "enablepassword"},
)

device.open()

Load a candidate configuration

device.load_merge_candidate(filename="new_config.txt")

Preview the diff before committing

diff = device.compare_config() if diff: print("Configuration diff:") print(diff) confirm = input("Apply changes? (yes/no): ") if confirm.lower() == "yes": device.commit_config() print("Configuration applied successfully.") else: device.discard_config() print("Changes discarded.") else: print("No changes detected.") device.discard_config() device.close()

This workflow — load, diff, confirm, commit — mirrors professional change management practices and dramatically reduces the risk of unintended configuration changes.

Useful NAPALM Getters

NAPALM provides a rich set of pre-built “getter” methods that return structured data:

Method What It Returns
get_facts() Hostname, OS version, uptime, serial number
get_interfaces() Interface status, speed, description
get_bgp_neighbors() BGP peer state and statistics
get_arp_table() ARP entries with IP and MAC mappings
get_route_to() Routing information for a specific prefix
get_config() Running, startup, or candidate configuration

These getters return consistent data structures regardless of the vendor, which means you can write inventory or compliance scripts that work across your entire mixed-vendor environment.


Netmiko vs. NAPALM: Choosing the Right Tool

A common question among engineers starting out with network automation is which library to learn first. The honest answer is that these tools are complementary, not competing.

Use Netmiko When:

  • You need to interact with devices that NAPALM does not support
  • You are working with legacy equipment that only supports SSH with a CLI
  • You need to run arbitrary show commands and process the output yourself
  • You want fine-grained control over the SSH session

Use NAPALM When:

  • You want structured, vendor-agnostic data without writing parsers
  • You need configuration diff and rollback capabilities
  • You are building tools that need to work across multiple vendors consistently
  • You are integrating with automation platforms like Ansible or Nornir

In practice, many experienced network engineers use both in the same projects. NAPALM handles the structured data collection and configuration management, while Netmiko fills in the gaps for one-off commands or unsupported devices.


Scaling Up: Connecting to Multiple Devices

Real network automation rarely involves a single device. Here is a simple example using a device inventory and Netmiko to collect show version output from multiple routers:

from netmiko import ConnectHandler
from concurrent.futures import ThreadPoolExecutor

inventory = [
    {"device_type": "cisco_ios", "host": "192.168.1.1", "username": "admin", "password": "pass123", "secret": "enable123"},
    {"device_type": "cisco_ios", "host": "192.168.1.2", "username": "admin", "password": "pass123", "secret": "enable123"},
    {"device_type": "juniper_junos", "host": "192.168.1.3", "username": "admin", "password": "pass123"},
]

def get_version(device):
    try:
        with ConnectHandler(**device) as conn:
            if device.get("secret"):
                conn.enable()
            output = conn.send_command("show version")
            return {"host": device["host"], "output": output}
    except Exception as e:
        return {"host": device["host"], "error": str(e)}

with ThreadPoolExecutor(max_workers=5) as executor:
    results = list(executor.map(get_version, inventory))

for result in results:
    print(f"n--- {result['host']} ---")
    print(result.get("output", result.get("error")))

Using ThreadPoolExecutor allows connections to run in parallel, which becomes critical when you are working with dozens or hundreds of devices.


Conclusion

Python has become an essential skill for modern network engineers, and Netmiko and NAPALM are two of the most valuable tools in your automation toolkit. Netmiko gives you low-level SSH access and the ability to interact with virtually any device through its CLI, while NAPALM provides a clean, vendor-agnostic abstraction layer with structured data and robust configuration management capabilities.

Start small. Automate one repetitive task, learn how each library behaves with your devices, and build from there. The investment in learning network programming pays dividends quickly — both in time saved and in the quality and consistency of your network operations.

Tags :

Kunal Nagaria

Recent News

Recommended

Subscribe Us

Get the latest creative news from BlazeTheme

    Switch on. Learn more

    Gadget

    World News

    @2023 Packet-Switched- All Rights Reserved