NETMIKO – FOR
NETWORK ENGINEER
NETWORK AUTOMATION WITH NETMIKO
13-APRIL-2025
TOPOLOGY
NETMIKO
1 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
INTRODUCTION - WHAT IS NETMIKO?
In today’s digital age, networks are the nervous system of every organization. From startups to
global enterprises, businesses rely on complex, interconnected systems to ensure seamless
operations, high availability, and secure communications. As these networks grow in scale and
complexity, the traditional approach of manually logging into each device for configuration or
troubleshooting becomes impractical, inefficient, and error prone.
That’s where network automation steps in as a game-changer.
THE SHIFT FROM MANUAL TO AUTOMATED NETWORKING
Traditionally, network engineers used CLI (Command-Line Interface) to configure routers, switches,
and firewalls one by one. While this method offers full control, it doesn't scale. Imagine updating a
simple ACL across hundreds of devices — manually. The risk of misconfigurations, delays, and fatigue
increases exponentially.
Enter Network Automation — the practice of programmatically managing and configuring network
devices. It speeds up operations, reduces human error, and ensures consistency across the network.
WHY NETMIKO?
Among various tools available for network automation, Netmiko stands out for its simplicity and
power. Developed by Kirk Byers, Netmiko is a Python library that simplifies SSH connections to
network devices. It builds on the low-level Paramiko library and adds device-specific enhancements
that are essential for network automation.
Netmiko supports devices from:
• Cisco (IOS, NX-OS)
• Juniper (JunOS)
• Arista (EOS)
• HP, Palo Alto, Fortinet, and many more.
WHO SHOULD READ THIS GUIDE?
• Beginner network engineers who are starting their journey in automation
• Experienced professionals looking to improve operational efficiency
• DevOps engineers who want to include network infrastructure into CI/CD workflows
2 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
NETWORK TOPOLOGY – NETMIKO
The Linux server connects to the Cisco router via SSH to apply configuration using Netmiko scripts:
Components:
• Control Node ( Linux Server {Python + Netmiko} )
• Cisco IOS Router
• SSH Connectivity between the Server and Router
3 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
UNDERSTANDING NETMIKO CONCEPT
At its core, Netmiko is a Python library that simplifies the process of communicating with network
devices over SSH. It abstracts away the complexity of establishing a secure session, handling
prompts, sending commands, and retrieving output — all using simple Python scripts.
Netmiko is built on top of Paramiko (a low-level SSH library), but it adds network device awareness.
This means Netmiko knows how to handle command prompts, timing issues, and quirks specific to
platforms like Cisco IOS, Juniper JunOS, and others.
Key Concepts:
• ConnectHandler: A class that creates an SSH session with the device.
• send_command(): Used to send read-only commands (e.g., show ip int brief).
• send_config_set(): Used to send configuration mode commands (e.g., interface settings,
routing protocols).
• Graceful disconnect: Automatically handles cleanup and logout from the session.
• Platform support: Works with over 60+ network platforms.
Netmiko is ideal for those who want to automate without the overhead of learning more complex
frameworks initially (like Ansible or Nornir).
BENEFITS OF USING NETMIKO FOR NETWORK
AUTOMATION
Netmiko provides a balanced entry point between manual CLI work and full-scale automation
frameworks.
• Simplicity & Speed - With just a few lines of Python, engineers can log into devices, gather
outputs, and make changes — instantly saving hours of manual work.
• Device Awareness - It handles Cisco-specific modes (enable, config terminal, etc.), line
endings, and command delays — so you don’t have to worry about writing logic to manage
them.
• Cross-vendor Support - Supports multiple vendors like Cisco, Juniper, Arista, HP, Fortinet,
Palo Alto, etc. — making it a one-stop solution in a multi-vendor environment.
• Integration Ready - Netmiko can be easily combined with version control (Git), scheduling
tools (cron, Jenkins), and inventory tools (Excel, NetBox) — making it automation-ready for
larger workflows.
• Error Handling - Provides built-in exception handling for SSH failures, timeouts, and
authentication errors — essential for production-grade automation.
4 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
REAL-WORLD USE CASE - CISCO + NETMIKO
Scenario: Automating Branch Router Provisioning
Use Case: An organization with 50+ branch offices wants to standardize and automate the
configuration of newly deployed Cisco routers.
Manual Steps (Without Automation):
• Log in via SSH to each router
• Set hostname, interface IPs
• Configure routing (OSPF or static)
• Save configuration
• Repeat for each device
With Netmiko:
A Python script with a CSV file of device IPs does the following:
- Reads device list
- Logs into each router
- Applies standard config (hostname, interfaces, OSPF)
- Saves config
- Logs out and reports status
Benefits Realized:
• Time Saved: What took 2 hours now takes 5 minutes
• Consistency: All routers get the exact same configuration template
• Error Reduction: Eliminates fat-finger errors in manual typing
• Scalability: Script can scale to 500+ routers with no extra effort
Bonus:
The configuration script is version-controlled in Git. Any change to the config template triggers a
GitHub Action that runs the Netmiko script in a CI/CD fashion — introducing true Network-as-
Code.
5 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
HOW TO SET UP NETMIKO IN LINUX
1. Install Python and pip
sudo apt update
sudo apt install python3 python3-pip -y
2. (Optional) Create virtual environment
python3 -m venv netmiko_env
source netmiko_env/bin/activate
3. Install Netmiko
pip install netmiko
4. Verify
python3
>>> import netmiko
>>> exit()
NETMIKO CONCEPTS - KEY DEFINITIONS
• SSH Connection: Automates SSH sessions to routers/switches.
• send_command(): For running “show” or read-only commands.
• send_config_set(): For sending configuration commands.
• TextFSM Integration: Parses raw CLI output into structured data.
• Error Handling: Built-in support for timeouts and auth failures.
6 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
BREAKING DOWN NETMIKO FUNCTIONS
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'host': '192.168.1.1',
'username': 'admin',
'password': 'cisco',
}
net_connect = ConnectHandler(**device)
output = net_connect.send_command("show ip int brief")
print(output)
net_connect.disconnect()
• ConnectHandler: Connects to device
• send_command(): Executes read-only CLI commands
• send_config_set(): Sends list of config commands
• disconnect(): Closes SSH session
7 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
CISCO IOS CONFIGURATION VIA NETMIKO
commands = [
'hostname R1,
'interface GigabitEthernet0/0',
'ip address 192.168.1.1 255.255.255.0',
'no shutdown',
'exit',
'ip routing'
]
output = net_connect.send_config_set(commands)
print(output)
This script configures interface IP, enables routing, and sets the hostname.
OUTPUT ON LINUX AND CISCO DEVICES
From Linux Terminal:
Interface IP-Address OK? Method Status Protocol
GigabitEthernet0/0 192.168.1.1 YES manual up up
Cisco CLI:
R1#show run
hostname AutoRouter
interface GigabitEthernet0/0
ip address 192.168.1.1 255.255.255.0
no shutdown
!
ip routing
8 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
ADVANCED NETMIKO USE CASES
1. BULK DEVICE AUTOMATION EXAMPLE
devices = [
{'device_type': 'cisco_ios', 'ip': '192.168.1.1', 'username': 'admin', 'password': 'cisco'},
{'device_type': 'cisco_ios', 'ip': '192.168.1.2', 'username': 'admin', 'password': 'cisco'}
]
for device in devices:
net_connect = ConnectHandler(**device)
output = net_connect.send_command('show version')
print(f"Output from {device['ip']}:\n{output}")
net_connect.disconnect()
2. ERROR HANDLING + LOGGING
from netmiko import NetMikoTimeoutException, NetMikoAuthenticationException
try:
net_connect = ConnectHandler(**device)
output = net_connect.send_command('show version')
print(output)
net_connect.disconnect()
except (NetMikoTimeoutException, NetMikoAuthenticationException) as e:
print(f"Connection failed: {e}")
3. SECURING CREDENTIALS
Never store passwords in your repo. Use GitHub Secrets instead:
1. Go to your GitHub repo > Settings > Secrets
2. Add:
o ROUTER_USERNAME
o ROUTER_PASSWORD
Modify the script to use os.environ:
import os
device = {
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': os.environ['ROUTER_USERNAME'],
9 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
'password': os.environ['ROUTER_PASSWORD']
}
In the workflow:
env:
ROUTER_USERNAME: ${{ secrets.ROUTER_USERNAME }}
ROUTER_PASSWORD: ${{ secrets.ROUTER_PASSWORD }}
4. AUTOMATE DAILY BACKUPS WITH NETMIKO
a. Folder Structure
netmiko-backup/
├── backups/
│ └── (backup files will be saved here)
├── device_inventory.yaml
├── backup_config.py
├── requirements.txt
b. device_inventory.yaml
devices:
- device_type: cisco_ios
ip: 192.168.1.1
username: admin
password: cisco
c. backup_config.py
import yaml
from netmiko import ConnectHandler
from datetime import datetime
from pathlib import Path
def load_devices(file_path='device_inventory.yaml'):
with open(file_path, 'r') as f:
return yaml.safe_load(f)['devices']
def backup_config(device):
10 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
connection = ConnectHandler(**device)
hostname = connection.send_command('show run | include hostname').strip().split()[-1]
running_config = connection.send_command('show running-config')
# Save to file
backup_dir = Path("backups")
backup_dir.mkdir(exist_ok=True)
filename = f"{hostname}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
filepath = backup_dir / filename
with open(filepath, 'w') as file:
file.write(running_config)
print(f"Backup saved: {filepath}")
connection.disconnect()
if __name__ == "__main__":
devices = load_devices()
for device in devices:
backup_config(device)
d. requirements.txt
netmiko
pyyaml
e. Automate with Cron (Linux Example)
crontab -e
Add a job to run every day at 2 AM:
0 2 * * * /usr/bin/python3 /path/to/netmiko-backup/backup_config.py
f. Sample Backup Output
Example file: backups/AutoRouter_20250413_020000.txt
Building configuration...
Current configuration : 2048 bytes
!
hostname AutoRouter
interface Loopback0
ip address 1.1.1.1 255.255.255.255
...
11 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
NETMIKO + DEVOPS (CI/CD INTEGRATION)
In the modern networking era, network configurations are no longer done in isolation. They're
treated like software — version-controlled, automated, and deployed through CI/CD pipelines. This is
where Netmiko meets DevOps.
WHAT IS CI/CD FOR NETWORK ENGINEERS?
• CI (Continuous Integration): The process of automatically testing and validating code (or
network configs) as soon as it's committed.
• CD (Continuous Deployment/Delivery): Automatically pushing those validated changes to
production (in our case, a router or switch).
HOW NETMIKO FITS IN
Netmiko acts as the deployment engine in the CI/CD pipeline. When you push a config update to
GitHub, the pipeline does the rest:
Example Workflow
1. Engineer updates network config script and commits to GitHub.
2. GitHub Actions detects the change.
3. Netmiko script runs inside a GitHub Actions runner or Jenkins agent.
4. The script logs into the router, pushes the configuration, and logs out.
5. Success/failure is reported in the CI/CD dashboard.
Tools Used
• GitHub or GitLab (Version control + trigger)
• GitHub Actions or Jenkins (Automation)
• Python + Netmiko (Execution engine)
• Cisco Routers (Target devices)
Security Considerations
• Use GitHub Secrets or Jenkins credentials plugin to manage device passwords.
• Only allow read-only configuration in CI; push to production via a "Promote to Live" step.
Coming Up Next...
In the next document, I’ll walk you through a real-world pipeline with:
• GitHub repo setup
• Dynamic inventory handling
• Rollbacks and versioning
Stay tuned. The future of networking is code + automation.
12 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!
FINAL THOUGHTS & CALL TO ACTION
Let’s wrap it all up.
You’ve just learned how to go from a manual CLI configuration to fully automated Netmiko —
all using Python.
KEY TAKEAWAYS
Netmiko is a lightweight but powerful Python tool that automates SSH access to network devices.
With just a few lines of code, you can push configs, collect data, or backup devices.
When integrated with Git and CI/CD tools, Netmiko transforms your network into infrastructure-
as-code (IaC).
This approach increases reliability, speed, and visibility in network operations.
WHO SHOULD USE THIS?
• Network Engineers wanting to upskill into DevNet/NetDevOps.
• DevOps teams integrating network workflows into CI/CD.
• IT Managers aiming for standardization and automation.
13 NETMIKO | By Meraj Hassan – Keep Calm & Automation On!