Python for Network Engineers
In this post I will cover in detail 7 Python scripts that I use as a Network Engineer to make my life easier.
For each example that needs connectivity I will be using a basic topology of 20 x CSR routers.
I will also be using Netmiko to connect to the network devices. If you have not used Netmiko before you can check this quick run through of creating a connection to a Cisco router using Netmiko.
If you are being told you need to learn or implement network automation these scripts should get you started.
Python programming for network engineers is becoming a must have skill in 2020. So you need to make sure you understand your objects, variables, methods, functions, dictionaries and lists. As one of the most popular programming languages in use today, there is so much information available, the scripts below should get you started.
If you want to download all the scripts you can git clone the repository with this command:
git clone https://github.com/rogerperkin/python-scripts-for-network-engineers.git
Page Contents
1. Python script to SSH to router
So the first script I am going to show you is how to SSH to a router.
This script uses Netmiko to make the connection and then I will run ‘show ip interface brief’ command to verify the ip interfaces on the router.
Script on Github: ssh-to-router.py
from netmiko import ConnectHandler #First create the device object using a dictionary CSR = { 'device_type': 'cisco_ios', 'ip': '192.168.1.220', 'username': 'roger', 'password': 'cisco' } # Next establish the SSH connection net_connect = ConnectHandler(**CSR) # Then send the command and print the output output = net_connect.send_command('show ip int brief') print (output) # Finally close the connection net_connect.disconnect()
This is a very basic script, which first imports from Netmiko the ConnectHandler.
Note: To run this you must have first installed Netmiko – if you have not please watch the video at the top of this post.
We then define a device called CSR and provide the information that Netmiko requires, which are device_type, IP address and a username and password.
Then using the net_connect module you connect to the device CSR
Once connected we send the command ‘sh ip int brief’ to the router and save the value as output
Finally we print output and disconnect from the device.
2. SSH to multiple routers
Now we have a basic connection to a single router, it’s time to scale it out, we are now going to connect to 5 routers. But it could easily be 100 or 1000!
For this I have created a new file called devices.txt which contains all the IP addresses of our 5 x CSR routers. We then use the same script but loop through the connection and pass in the IP of each router so we can get the ‘sh ip int brief’ output of all the routers.
192.168.1.220 192.168.1.221 192.168.1.222 192.168.1.223 192.168.1.224 192.168.1.225
NOTE: do not press enter at the end of the last line. Otherwise your script will have problems at the end.
# SSH to Multiple Devices from devices file from netmiko import ConnectHandler with open('devices.txt') as routers: for IP in routers: Router = { 'device_type': 'cisco_ios', 'ip': IP, 'username': 'roger', 'password': 'cisco' } net_connect = ConnectHandler(**Router) print ('Connecting to ' + IP) print('-'*79) output = net_connect.send_command('sh ip int brief') print(output) print() print('-'*79) # Finally close the connection net_connect.disconnect()
If your are doing this on scale you would be using a Python Automation Framework like Nornir. This gives you the benefit of an inventory, much like Ansible.
However, it’s still good to understand how to perform this task manually before jumping into other topics.
3. Python Script to backup Cisco config
Now we have established how to connect to multiple devices and can run basic commands, the next step is to be able to save that output.
One of the first tasks people usually take on when they get started with network automation is to take a backup of a configuration file. This Python script does just that.
from netmiko import ConnectHandler #First create the device object using a dictionary CSR = { 'device_type': 'cisco_ios', 'ip': '192.168.1.220', 'username': 'roger', 'password': 'cisco' } # Next establish the SSH connection net_connect = ConnectHandler(**CSR) #Discover the hostname from the prompt hostname = net_connect.send_command('show run | i host') hostname.split(" ") hostname,device = hostname.split(" ") print ("Backing up " + device) filename = '/home/roger/python-scripts-for-network-engineers/backups/' + device + '.txt' # to save backup to same folder as script use below line and comment out above line # filename = device + '.txt' showrun = net_connect.send_command('show run') showvlan = net_connect.send_command('show vlan') showver = net_connect.send_command('show ver') log_file = open(filename, "a") # in append mode log_file.write(showrun) log_file.write("\n") log_file.write(showvlan) log_file.write("\n") log_file.write(showver) log_file.write("\n") # Finally close the connection net_connect.disconnect()
Note: you need to change filename = to match your environment
4. Python script to backup multiple routers
Now we have a script that can backup a singe Cisco router it is very easy to take the script we used to connect to multiple routers and just add in the backup task to the for loop.
This script uses the devices.txt file again to loop through the list of IP’s and take a backup of each router.
All backups are placed in /backups but you can change the location of the backup by changing the path after filename.
# SSH to Multiple Devices from devices file from netmiko import ConnectHandler with open('devices.txt') as routers: for IP in routers: Router = { 'device_type': 'cisco_ios', 'ip': IP, 'username': 'roger', 'password': 'cisco' } net_connect = ConnectHandler(**Router) hostname = net_connect.send_command('show run | i host') hostname.split(" ") hostname,device = hostname.split(" ") print ("Backing up " + device) filename = '/home/roger/python-scripts-for-network-engineers/backups/' + device + '.txt' # to save backup to same folder as script use below line and comment out above line # filename = device + '.txt' showrun = net_connect.send_command('show run') showvlan = net_connect.send_command('show vlan') showver = net_connect.send_command('show ver') log_file = open(filename, "a") # in append mode log_file.write(showrun) log_file.write("\n") log_file.write(showvlan) log_file.write("\n") log_file.write(showver) log_file.write("\n") # Finally close the connection net_connect.disconnect()
5. Config Generator using Jinja2
6. IP Valid Checker
This simple Python script uses the ipaddress module and will validate if an entered IPv4 or IPv6 address is valid or not.
import os, ipaddress os.system('cls') while True: ip = input('Enter IP Address: ') try: print(ipaddress.ip_address(ip)) print('IP Valid') except: print:('-' *50) print('IP is not valid') finally: if ip =='q': print('Script Finished') break
This page is under constant development and as I use a new script I will be adding it here.
Topics to add:
netmiko, napalm, pyntc, telnet
Python Videos for Network Automation
Notes for development
Consider using pathlib when opening and writing to files
https://docs.python.org/3.9/library/pathlib.html
Hi, Roger. I see nothing listed underneath the “5. Config Generator using Jinja2”. Is it for future use? Thanks.
Hi Remy, yes – it’s a placeholder I need to finish the post!
Hi, Roger
Thanks for putting together this article with examples and images. Do you think you will be able to finish section 5? If not, no problem and thanks again!
Yes, I have it on my list of jobs to do!
Awesome. Thanks for your prompt reply, Roger. Look forward to it.
Hi Roger,
Very nice article. Can I have your permission to use the examples in one of our certificvation course content?
Thanks,
Jag Kang
Content Engineer
Cisco Systems
Of course – use what you like!