Network Automation Basics with Python and Netmiko

CCNP 9 min readPublished 2 November 2026

Quick answer

Learn how Python and Netmiko automate Cisco device configuration, verification and backups. Build a practical multi-device lab with safe troubleshooting steps.

Network engineers often repeat the same tasks across routers and switches: checking interfaces, collecting configurations, creating VLANs and validating routing neighbours. Network automation with Python reduces this manual work while producing consistent, repeatable results.

This guide introduces Netmiko through a practical Cisco IOS lab. You will connect to devices over SSH, run show commands, change configurations, save backups and troubleshoot common failures.

What is network automation with Python?

Network automation with Python means using scripts to configure, verify and monitor network devices instead of entering every command manually. Python provides the program logic, while libraries such as Netmiko handle SSH sessions and command execution.

Automation does not replace networking knowledge. You still need to understand routing, switching, addressing and Cisco IOS behaviour before a script can make safe decisions. These topics form an important practical layer within a CCNP Enterprise course.

Common automation tasks include:

  • Collecting interface status from multiple switches
  • Backing up running configurations
  • Creating VLANs consistently
  • Updating interface descriptions
  • Checking OSPF or BGP neighbours
  • Comparing expected and actual device state
  • Applying standard security settings
  • Producing reports for troubleshooting or audits

Python is useful because it supports variables, loops, conditions, functions and structured data. Instead of opening ten SSH sessions, a script can read an inventory and perform the same controlled operation on all ten devices.

How does Netmiko communicate with network devices?

Netmiko is a Python library designed for command-line connections to network equipment. It builds on SSH libraries and handles device-specific prompts, configuration modes, command timing and terminal pagination.

A diagram in words looks like this:

Python workstation
    |
    | SSH over TCP port 22
    v
Netmiko ConnectHandler
    |
    +---- R1: Cisco IOS router
    +---- R2: Cisco IOS router
    +---- SW1: Cisco IOS switch

Without Netmiko, a script must manage SSH channels, detect prompts and wait for command output. Netmiko provides methods designed for these operations.

Netmiko methodPurpose
ConnectHandler()Opens a connection using device details
send_command()Runs an operational command and reads its output
send_config_set()Enters configuration mode and applies commands
send_command_timing()Uses timing rather than prompt detection for interactive commands
save_config()Saves the active configuration on supported platforms
disconnect()Closes the SSH session cleanly

Netmiko supports many vendors, but each inventory entry must use the correct device_type. Cisco IOS and IOS XE devices normally use cisco_ios.

What lab topology is used in this tutorial?

The lab contains one automation workstation and three Cisco IOS devices reachable through a management network. You can build it in EVE-NG, CML, GNS3 or another environment that provides legal Cisco images.

Automation PC: 192.168.10.10
         |
   Management LAN
     /    |    \
    /     |     \
R1        R2     SW1
.11       .12    .21

Confirm that the workstation can ping every management address. SSH must also be enabled on each Cisco device.

A basic IOS SSH configuration is:

hostname R1
ip domain name lab.local
username automation privilege 15 secret Use-A-Strong-Lab-Secret
crypto key generate rsa modulus 2048
ip ssh version 2

line vty 0 4
 login local
 transport input ssh
 exec-timeout 10 0

Apply an IP address to the relevant management interface and ensure the device has a return route to the workstation. In production, use restricted management access, individual accounts, AAA and secure secret storage rather than embedding shared credentials in scripts.

Students who are not yet comfortable with IOS interfaces, IP addressing and SSH should establish those foundations through structured CCNA training before automating configuration changes.

How do you install Python and Netmiko?

Create a virtual environment so that the lab has isolated Python packages. Then install Netmiko with pip inside that environment.

On Linux or macOS:

python3 -m venv netauto-venv
source netauto-venv/bin/activate
python -m pip install --upgrade pip
python -m pip install netmiko

On Windows PowerShell:

py -m venv netauto-venv
.\netauto-venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install netmiko

Verify the installation:

python -c "import netmiko; print(netmiko.__version__)"

If the import fails, confirm that the script is running with the Python interpreter from the activated virtual environment.

How do you run a show command with Netmiko?

Create a device dictionary, pass it to ConnectHandler, and use send_command() to execute a read-only IOS command. Prompting for credentials is safer than placing passwords directly in source code.

Save this script as show_interfaces.py:

from getpass import getpass
from netmiko import ConnectHandler

username = input('Username: ')
password = getpass('Password: ')

device = {
    'device_type': 'cisco_ios',
    'host': '192.168.10.11',
    'username': username,
    'password': password,
}

connection = ConnectHandler(**device)
print(f'Connected to {connection.find_prompt()}')

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

connection.disconnect()

Run it with:

python show_interfaces.py

Example output may look like this:

Connected to R1#
Interface              IP-Address      OK? Method Status                Protocol
GigabitEthernet0/0     192.168.10.11   YES manual up                    up
GigabitEthernet0/1     10.0.12.1       YES manual up                    up
Loopback0              10.10.1.1       YES manual up                    up

Status represents the physical or administrative state, while Protocol represents the line protocol. An administratively down/down interface is shut down in the configuration. An up/down result requires further Layer 2 or protocol investigation.

Use try, finally or a context manager in larger programs so connections are closed even when a command fails.

How can Python automate several Cisco devices?

Store device-specific values in a list and process that list with a loop. Each device should have its own management address and any unique configuration values, such as a loopback IP address.

The following lab creates Loopback120 on two routers, verifies it and saves the configuration:

from getpass import getpass
from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoAuthenticationException
from netmiko.exceptions import NetmikoTimeoutException

username = input('Username: ')
password = getpass('Password: ')

devices = [
    {
        'name': 'R1',
        'device_type': 'cisco_ios',
        'host': '192.168.10.11',
        'loopback_ip': '172.20.120.1',
    },
    {
        'name': 'R2',
        'device_type': 'cisco_ios',
        'host': '192.168.10.12',
        'loopback_ip': '172.20.120.2',
    },
]

for device in devices:
    connection = None
    try:
        connection_data = {
            'device_type': device['device_type'],
            'host': device['host'],
            'username': username,
            'password': password,
        }

        connection = ConnectHandler(**connection_data)
        before = connection.send_command(
            'show running-config interface Loopback120'
        )
        print(f"\n{device['name']} configuration before change:\n{before}")

        commands = [
            'interface Loopback120',
            'description MANAGED_BY_PYTHON',
            f"ip address {device['loopback_ip']} 255.255.255.255",
            'no shutdown',
        ]

        result = connection.send_config_set(commands)
        print(result)

        verification = connection.send_command(
            'show ip interface brief | include Loopback120'
        )
        print(f"Verification on {device['name']}: {verification}")

        connection.save_config()

    except NetmikoAuthenticationException:
        print(f"Authentication failed on {device['name']}")
    except NetmikoTimeoutException:
        print(f"Connection timed out on {device['name']}")
    finally:
        if connection:
            connection.disconnect()

Notice that connection details are separated from configuration data before calling ConnectHandler. Netmiko would not recognise custom keys such as name or loopback_ip as connection parameters.

The script also verifies the result before saving. For a production change, add pre-change checks, configuration backups, maintenance approval and a tested rollback procedure.

How do you back up Cisco configurations with Python?

Run show running-config, create a unique filename and write the returned text to a protected directory. A timestamp prevents a newer backup from silently replacing an older file.

from datetime import datetime
from pathlib import Path
from netmiko import ConnectHandler

backup_dir = Path('backups')
backup_dir.mkdir(exist_ok=True)

connection = ConnectHandler(
    device_type='cisco_ios',
    host='192.168.10.11',
    username='automation',
    password='LAB_PASSWORD_ONLY',
)

hostname = connection.find_prompt().rstrip('#>')
timestamp = datetime.now().strftime('%Y%m%d-%H%M%S')
config = connection.send_command('show running-config', read_timeout=60)

filename = backup_dir / f'{hostname}-{timestamp}.cfg'
filename.write_text(config, encoding='utf-8')
connection.disconnect()

print(f'Backup written to {filename}')

The hard-coded password is shown only to keep this isolated example short. For operational scripts, retrieve secrets from an approved vault, environment-based secret injection or an interactive prompt. Restrict access to backups because running configurations may contain sensitive network information even when passwords are hashed.

How should command output be parsed?

Raw command output is readable but difficult to use reliably in conditions and reports. Structured parsing converts rows and fields into Python dictionaries or lists so the program can evaluate values directly.

Netmiko can use TextFSM templates when the required parser templates are installed:

python -m pip install ntc-templates
interfaces = connection.send_command(
    'show ip interface brief',
    use_textfsm=True
)

if isinstance(interfaces, list):
    for interface in interfaces:
        print(interface)
else:
    print('Structured parsing was unavailable; raw output returned')
    print(interfaces)

Do not assume that every command and software version has a matching template. Check the returned data type, test against the IOS versions in your environment and handle raw output safely. Avoid parsing complex output with fragile string positions because spacing can change between platforms.

What makes a network automation script safe?

A safe script separates inventory, credentials, configuration intent, execution and validation. It should fail clearly, limit its scope and produce enough logging to show what happened on each device.

Use this operational sequence:

Define intended state
        |
Validate inventory and reachability
        |
Collect and save pre-change state
        |
Apply a small controlled change
        |
Verify operational state
        |
Save, report or roll back

Important practices include:

  1. Test read-only commands before configuration commands.
  2. Use a lab that represents the target platform and IOS release.
  3. Keep credentials outside source code and version control.
  4. Validate IP addresses and device roles before connecting.
  5. Back up configurations before a change.
  6. Apply changes to one pilot device before a larger group.
  7. Verify state with show commands rather than trusting command acceptance.
  8. Catch authentication and timeout exceptions separately.
  9. Log device name, command stage, result and error details.
  10. Define rollback commands before starting the change.

Automation can repeat an error faster than a person can. Change control and networking knowledge therefore remain essential, especially for routing protocols covered in the CCNP ENARSI practical study order.

How do you troubleshoot common Netmiko errors?

Start by separating network reachability, SSH service, authentication, prompt handling and command execution. Test each layer independently instead of changing the Python script immediately.

SymptomLikely causeCheck or fix
Connection timeoutRouting, ACL, firewall or SSH unavailableTest ping and ssh user@device-ip; verify TCP 22
Authentication failureWrong credentials or AAA policyTest manual SSH with the same account
Unsupported device typeIncorrect Netmiko platform valueUse cisco_ios for normal IOS and IOS XE CLI sessions
Prompt not detectedUnusual banner, prompt or slow deviceCheck the manual login flow and increase read_timeout where appropriate
Command ends earlyDevice output takes longer than expectedSet a suitable read_timeout in send_command()
Configuration rejectedWrong syntax, mode or platform featureReview returned IOS error lines and test commands in the lab
TextFSM returns a stringNo matching template or parsing failureCheck ntc-templates and handle raw output

From the workstation, test the port directly:

ssh automation@192.168.10.11

On Cisco IOS, inspect SSH status and active lines:

show ip ssh
show users
show line
show logging

If commands work manually but not through Netmiko, print the detected prompt with find_prompt() and enable Python logging during diagnosis:

import logging

logging.basicConfig(filename='netmiko-debug.log', level=logging.DEBUG)

Debug logs may contain device output and operational details. Store them securely, review them before sharing and disable detailed logging when it is no longer required.

What should you learn after basic Netmiko?

After basic SSH automation, learn structured data, reusable functions, exception handling, testing and source control. You can then progress to APIs, NETCONF or RESTCONF, data models, configuration templates and larger automation frameworks.

A practical learning order is:

  1. Python variables, loops, functions and dictionaries
  2. JSON and YAML data
  3. Netmiko show commands and configuration changes
  4. TextFSM or another structured parser
  5. Jinja2 configuration templates
  6. Git and code review
  7. NETCONF, RESTCONF and YANG concepts
  8. Automated validation and CI workflows

The goal is not only to make a script run. A network engineer must be able to explain its scope, inputs, expected state, failure behaviour and rollback process.

Summary

Network automation Python workflows use code to perform repeatable network tasks, while Netmiko simplifies SSH interaction with Cisco IOS and other platforms. Start with read-only collection, move to backed-up lab changes, and always verify the resulting device state.

Useful first projects include configuration backups, interface reports and standard loopback deployment. Keep credentials secure, parse output carefully and test every failure path before using automation on operational equipment.

To practise Python automation alongside enterprise routing, switching and troubleshooting, enquire about lab coverage and batch details for the CCNP Enterprise course.

Reviewed by Network Rhinos networking trainers.

Frequently asked questions

What is Netmiko used for in network automation?

Netmiko is used to connect to network devices over SSH and execute CLI commands. It handles prompts, configuration mode, command timing and output collection for platforms such as Cisco IOS.

Do I need advanced Python knowledge to learn Netmiko?

No. You can begin with Python variables, dictionaries, lists, loops, functions and exception handling. Networking knowledge is equally important because you must understand the commands and validate their effect.

Can Netmiko configure multiple Cisco devices?

Yes. A Python script can loop through an inventory and connect to each device using Netmiko. Device-specific values should be stored separately, and every configuration change should include backup and verification steps.

What is the correct Netmiko device type for Cisco IOS?

Use `cisco_ios` for standard Cisco IOS and IOS XE command-line sessions. Using the wrong device type can cause prompt detection, command execution or configuration mode failures.

Is it safe to store Cisco passwords in a Python script?

No. Hard-coded passwords can be exposed through source control, backups or file access. Use an interactive password prompt or an approved secret-management system for operational automation.

What should I automate first with Python and Netmiko?

Begin with read-only tasks such as collecting interface status and backing up configurations. After validating error handling and logging, move to small lab changes with pre-checks, post-checks and rollback commands.

Related articles

Train with Network Rhinos

Hands-on CCNA, CCNP, AWS, Azure, DevOps and cybersecurity training in Chennai & Bangalore, with placement support. Talk to our team or attend a free demo class.