Hello, young network engineer! You now know how networks work, how to write socket programs, and how to use APIs. Now it's time to learn how Python can help us control and manage network devices like routers and switches.
Imagine you are a network engineer. You have to configure 100 routers in different cities. Doing it manually would take days! But what if you could write a single Python script that configures all 100 routers in minutes? That's network automation.
In this module, we will learn how to use Python to connect to network devices using SSH and Telnet. We will use libraries like Paramiko and Netmiko to send commands and automate tasks. We will also explore NAPALM for managing multiple device types.
By the end of this module, you will be able to write Python scripts that automate network configuration, monitoring, and troubleshooting.
After reading this module, you will be able to:
paramiko library for SSH connections.netmiko library for simplified device management.napalm library for multi-vendor automation.In a busy city called Networkville, there was a network engineer named Kelechi. He was responsible for 100 routers across the city. Every time he needed to update a configuration, he had to log into each router manually – one by one. It took him days!
One day, Kelechi discovered Python. He wrote a script that could log into all the routers at once, send the same commands, and even back up the configurations. Now he could finish his work in minutes and spend the rest of the day having fun.
Kelechi became a hero in Networkville. He taught other engineers how to use Python for automation. Soon, everyone was using Python to save time and avoid mistakes.
This is exactly what network automation does – it uses Python to talk to network devices and make them do work automatically.
Definition: Network automation is using software (like Python) to automatically manage and configure network devices.
Why it is important: It saves time, reduces human errors, and makes networks more reliable.
Simple explanation: Like using a remote control to turn on all the lights in your house at once instead of walking to each switch.
Real-life example: A company uses Python to push updates to all its routers.
School example: The IT team uses automation to configure all computers in the lab.
Home example: You could write a script to restart your router automatically.
Nigerian example: A Nigerian telecom uses automation to manage its network towers.
Manual: [Login to each device] -> [Send commands] -> [Logout] (repeat 100 times)
Automation: [Script] -> [Login to all devices] -> [Send commands] -> [Done]
Mini summary: Network automation uses software to manage networks automatically.
Definition: SSH (Secure Shell) and Telnet are protocols for remotely connecting to devices. SSH is secure; Telnet is older and less secure.
Why it is important: You need a way to talk to network devices.
Simple explanation: Like a telephone line to your router.
Real-life example: Network engineers use SSH to configure switches.
School example: The IT teacher uses SSH to manage the school's server.
Home example: Some home routers allow SSH access.
Nigerian example: Nigerian companies use SSH for secure remote management.
| Feature | SSH | Telnet |
|---|---|---|
| Security | Secure (encrypted) | Not secure (plain text) |
| Port | 22 | 23 |
| Use | Modern networks | Legacy systems |
Mini summary: SSH is secure; Telnet is not. Always use SSH.
Definition: Paramiko is a Python library for SSH connections. It lets you log into devices and send commands.
Why it is important: It is the foundation for SSH automation in Python.
Simple explanation: Like a key that opens the door to your router.
Real-life example: Network engineers use Paramiko to automate SSH tasks.
School example: Students can use Paramiko to practice automation.
Home example: You can use Paramiko to manage your home router.
Nigerian example: Nigerian developers use Paramiko for automation projects.
pip install paramiko # Install the library
Mini summary: Paramiko is the library for SSH in Python.
Definition: You create an SSH client, connect to the device, and send commands.
Why it is important: This is how you talk to a device.
Simple explanation: Like dialing a phone number and speaking to someone.
Real-life example: A script that connects to a router and runs 'show version'.
School example: A script to check the status of the school's network.
Home example: A script to check the uptime of your router.
Nigerian example: A script to check the health of a bank's network.
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.1.1', username='admin', password='password')
stdin, stdout, stderr = client.exec_command('show version')
print(stdout.read().decode())
client.close()
Mini summary: Paramiko lets you connect and run commands over SSH.
Definition: Netmiko is a Python library built on top of Paramiko. It makes SSH automation even easier by handling device-specific details.
Why it is important: It works with many different devices (Cisco, Juniper, etc.) with the same code.
Simple explanation: Like a universal remote that works on all TVs.
Real-life example: A company uses Netmiko to manage both Cisco and Juniper routers.
School example: Students learn Netmiko to automate device configuration.
Home example: You can use Netmiko to manage your router if it supports SSH.
Nigerian example: Nigerian network engineers use Netmiko for automation.
pip install netmiko
Mini summary: Netmiko is a powerful, easy-to-use library for network automation.
Definition: You create a connection dictionary and use ConnectHandler to connect.
Why it is important: It simplifies the connection process.
Simple explanation: Like telling the remote control what TV you have.
Real-life example: A script connects to a Cisco router and runs a command.
School example: A script to get the interface status of the school switch.
Home example: A script to check your router's configuration.
Nigerian example: A script to check the status of a bank's network devices.
from netmiko import ConnectHandler
device = {
'device_type': 'cisco_ios',
'ip': '192.168.1.1',
'username': 'admin',
'password': 'password'
}
connection = ConnectHandler(**device)
output = connection.send_command('show version')
print(output)
connection.disconnect()
Mini summary: Netmiko makes connecting to devices very easy.
Definition: You can send multiple commands to a device in one go.
Why it is important: It saves time and reduces the number of connections.
Simple explanation: Like giving a list of instructions to someone instead of one at a time.
Real-life example: A script that configures an interface, sets an IP, and enables it.
School example: A script to configure a lab switch.
Home example: A script to update your router's settings.
Nigerian example: A script to configure a new router in a branch office.
commands = [
'interface gig0/0',
'ip address 192.168.1.1 255.255.255.0',
'no shutdown'
]
output = connection.send_config_set(commands)
print(output)
Mini summary: Send many commands at once with send_config_set().
Definition: After making changes, you need to save them to the device's startup configuration.
Why it is important: If you don't save, changes are lost when the device restarts.
Simple explanation: Like saving a document after editing it.
Real-life example: A script runs 'write memory' to save the config.
School example: A script saves the switch configuration after a lab.
Home example: A script saves your router's settings.
Nigerian example: A script saves a bank router's configuration.
output = connection.send_command('write memory')
print(output)
# For some devices: copy running-config startup-config
Mini summary: Always save your changes!
Definition: You can back up the running configuration of a device to a file.
Why it is important: It helps you recover if something goes wrong.
Simple explanation: Like making a copy of your homework.
Real-life example: A script that backs up all router configs every night.
School example: A script that backs up the school's switch configs.
Home example: A script that backs up your router's config.
Nigerian example: A script that backs up bank router configs.
output = connection.send_command('show running-config')
with open('backup.txt', 'w') as f:
f.write(output)
Mini summary: Backing up configs is a best practice.
Definition: NAPALM (Network Automation and Programmability Abstraction Layer) is a library that allows you to manage different types of devices (Cisco, Juniper, etc.) with the same code.
Why it is important: It helps you write code that works on any device.
Simple explanation: Like a universal translator for network devices.
Real-life example: A company uses NAPALM to manage a mix of Cisco and Juniper devices.
School example: Students use NAPALM to practice on different simulated devices.
Home example: Not common at home, but useful for learning.
Nigerian example: Nigerian companies with diverse device types use NAPALM.
pip install napalm
Mini summary: NAPALM makes automation work across different vendors.
Definition: You create a driver for your device type and use methods like get_facts() and get_interfaces().
Why it is important: It standardizes how you get information from devices.
Simple explanation: Like ordering food from a menu – you get the same result regardless of the restaurant.
Real-life example: A script gets interface status from all devices.
School example: A script to check interface status for a lab.
Home example: Not common at home.
Nigerian example: A script to check interface status across different vendors.
from napalm import get_network_driver
driver = get_network_driver('ios')
device = driver('192.168.1.1', 'admin', 'password')
device.open()
facts = device.get_facts()
interfaces = device.get_interfaces()
print(facts)
print(interfaces)
device.close()
Mini summary: NAPALM provides a consistent way to manage devices.
Definition: Things can go wrong – wrong password, device unreachable, etc. Use try/except to handle errors.
Why it is important: Prevents your script from crashing.
Simple explanation: Like having a backup plan if something goes wrong.
Real-life example: A script tries 3 times before giving up.
School example: A script handles a connection failure gracefully.
Home example: A script shows a friendly message if the router is offline.
Nigerian example: A script handles a timeout when a device is slow.
try:
connection = ConnectHandler(**device)
output = connection.send_command('show version')
except Exception as e:
print(f"Error: {e}")
finally:
if connection:
connection.disconnect()
Mini summary: Error handling makes your scripts robust.
Definition: Don't hardcode passwords in your scripts. Use environment variables or a config file.
Why it is important: It's more secure and easier to manage.
Simple explanation: Like keeping your keys in a safe place, not on the floor.
Real-life example: A script reads the password from an environment variable.
School example: Students store credentials in a .env file.
Home example: Your script reads the password from a file.
Nigerian example: A company uses a secret manager for credentials.
import os
password = os.getenv('DEVICE_PASSWORD', 'default')
Mini summary: Keep credentials safe and separate from your code.
Definition: You can use Python to push configuration changes to multiple devices.
Why it is important: This is the core of network automation.
Simple explanation: Like sending a group message to update everyone's schedule.
Real-life example: A script that changes the SNMP community string on all routers.
School example: A script that changes the hostname of all lab switches.
Home example: A script that updates your router's DNS settings.
Nigerian example: A script that updates the banner on all company routers.
devices = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
for ip in devices:
device = {'device_type': 'cisco_ios', 'ip': ip, 'username': 'admin', 'password': 'pass'}
conn = ConnectHandler(**device)
conn.send_config_set(['banner motd #Welcome to Automated Network#'])
conn.disconnect()
Mini summary: You can automate configuration changes across many devices.
Definition: Best practices for writing safe and reliable automation scripts.
Why it is important: To avoid accidentally breaking the network.
Simple explanation: Like driving carefully to avoid accidents.
Best practices:
# Best practice: validate before applying changes
# Best practice: use dry-run mode to test changes
Mini summary: Best practices keep your network safe and your scripts reliable.
Teachers, this module is best taught with hands-on labs. If possible, set up virtual devices (e.g., GNS3, EVE-NG) or use Cisco DevNet Sandbox. Emphasize the importance of error handling and best practices. Encourage students to write scripts for simple tasks and build up to more complex automation.
Parents, help your child understand that automation is about making work easier. If you have a router at home, you can let them practice (with supervision). Talk about how automation is used in everyday life – from cars to factories. Encourage them to think about what they can automate.
+----------------+
| Python Script |
+----------------+
|
V
+----------------+
| SSH / Netmiko |
+----------------+
|
V
+----------------+ +----------------+
| Router 1 |-----| Router 2 |
+----------------+ +----------------+
| |
+-----------+-----------+
|
+----------------+
| Router 3 |
+----------------+
Client (Python) ---- SSH ----> Device
Client (Python) <-- Response -- Device
+----------------+
| Start Script |
+----------------+
|
V
+----------------+
| Connect to |
| Device |
+----------------+
|
V
+----------------+
| Send 'show |
| running-config'|
+----------------+
|
V
+----------------+
| Save output to |
| file |
+----------------+
|
V
+----------------+
| Disconnect |
+----------------+
| Feature | Paramiko | Netmiko |
|---|---|---|
| Ease of use | Moderate | Easy |
| Device support | Generic | Many vendors |
| Command handling | Manual | Automatic (with prompts) |
| Best for | Custom SSH tasks | Network automation |
| Feature | SSH | Telnet |
|---|---|---|
| Encryption | Yes | No |
| Security | High | Low |
| Port | 22 | 23 |
| Use | Modern networks | Legacy systems |
Fantastic work! You have completed Module 4: Network Automation – Python for Network Devices.
You learned about network automation and why it is important. You explored SSH and Telnet and understood why SSH is preferred. You used the paramiko library for SSH connections and netmiko for easier automation. You also learned about NAPALM for multi-vendor support.
You learned how to send commands, back up configurations, and handle errors. You also learned best practices to keep your automation safe and reliable. You are now ready to automate real network devices!
Match the term on the left with the correct definition on the right.
| Term | Definition |
|---|---|
| 1. SSH | A. Multi-vendor automation library |
| 2. Telnet | B. Secure remote connection |
| 3. Paramiko | C. Unsecure remote connection |
| 4. Netmiko | D. Python SSH library |
| 5. NAPALM | E. Simplified network automation |
Answers: 1-B, 2-C, 3-D, 4-E, 5-A
Scenario 1: You are a network engineer for a Nigerian company. You need to update the SNMP community string on 50 routers. How would you automate this?
Scenario 2: Your company has a mix of Cisco and Juniper routers. You need to get the interface status from all of them. Which library would you use and why?
Scenario 3: You run a script to change a configuration, but it fails on one device because of a wrong password. How would you handle this?
Design an Automation Project: In groups, design a network automation project. Define the problem, choose the tools (Paramiko, Netmiko, NAPALM), and write a script to solve the problem. Present your project to the class.
Write a Backup Script: Write a Python script using Netmiko that connects to a device, retrieves the running configuration, and saves it to a file with the device name. Test it on a lab device.
Build a Device Inventory Script: Build a Python script that connects to multiple devices, retrieves basic information (hostname, model, software version), and writes it to a CSV file. Use Netmiko and handle errors.
Automate a Configuration Update: Write a script that updates the DNS server setting on all devices in a list. Include saving the configuration and error handling. Test on lab devices.
Build a Multi-Vendor Automation Script: Use NAPALM to connect to a Cisco and a Juniper device. Retrieve the interface status and list of configured VLANs from both. Display the data in a unified format.
Fill-in-the-Blank Answers:
True or False Answers: 1-F, 2-T, 3-T, 4-F, 5-F, 6-T, 7-F, 8-F, 9-F, 10-T
Multiple Choice Answers: 1-B, 2-B, 3-B, 4-B, 5-A, 6-B, 7-B, 8-B, 9-B, 10-C, 11-B, 12-A, 13-B, 14-C, 15-B
In Module 5, we will explore Advanced Network Automation. You will learn about version control for network configurations, using Ansible for automation, and advanced topics like RESTCONF and NETCONF.
To prepare, think about these questions:
You are now ready for Module 5. Keep automating and innovating!
🎉 Congratulations! You have completed Module 4: Network Automation – Python for Network Devices. See you in Module 5!