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 switchWithout Netmiko, a script must manage SSH channels, detect prompts and wait for command output. Netmiko provides methods designed for these operations.
| Netmiko method | Purpose |
|---|---|
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 .21Confirm 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 0Apply 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 netmikoOn Windows PowerShell:
py -m venv netauto-venv
.\netauto-venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
python -m pip install netmikoVerify 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.pyExample 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 upStatus 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-templatesinterfaces = 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 backImportant practices include:
- Test read-only commands before configuration commands.
- Use a lab that represents the target platform and IOS release.
- Keep credentials outside source code and version control.
- Validate IP addresses and device roles before connecting.
- Back up configurations before a change.
- Apply changes to one pilot device before a larger group.
- Verify state with show commands rather than trusting command acceptance.
- Catch authentication and timeout exceptions separately.
- Log device name, command stage, result and error details.
- 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.
| Symptom | Likely cause | Check or fix |
|---|---|---|
| Connection timeout | Routing, ACL, firewall or SSH unavailable | Test ping and ssh user@device-ip; verify TCP 22 |
| Authentication failure | Wrong credentials or AAA policy | Test manual SSH with the same account |
| Unsupported device type | Incorrect Netmiko platform value | Use cisco_ios for normal IOS and IOS XE CLI sessions |
| Prompt not detected | Unusual banner, prompt or slow device | Check the manual login flow and increase read_timeout where appropriate |
| Command ends early | Device output takes longer than expected | Set a suitable read_timeout in send_command() |
| Configuration rejected | Wrong syntax, mode or platform feature | Review returned IOS error lines and test commands in the lab |
| TextFSM returns a string | No matching template or parsing failure | Check ntc-templates and handle raw output |
From the workstation, test the port directly:
ssh automation@192.168.10.11On Cisco IOS, inspect SSH status and active lines:
show ip ssh
show users
show line
show loggingIf 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:
- Python variables, loops, functions and dictionaries
- JSON and YAML data
- Netmiko show commands and configuration changes
- TextFSM or another structured parser
- Jinja2 configuration templates
- Git and code review
- NETCONF, RESTCONF and YANG concepts
- 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.
