Python Network Automation
In this Python for network engineers tutorial I will cover in detail some useful Python scripts network engineers can start using today.
Looking for some more in depth training check out my Python Course for Network Engineers
Python for Network Engineers Scripts
These are scripts that I use on nearly a daily basis. By the end of this post you will learn that network engineers and Python do get along!
Python is easy to learn and very powerful.
Python Network Automation Scripts Examples
For each example that needs connectivity I will be using a basic topology of 20 x CSR routers.
Netmiko Tutorial
I will also be using Netmiko for connection 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.
Check out this great intro to Netmiko – there are more resources on my YouTube Channel
If you are being told you need to learn Python or implement network automation these scripts should get you started.
Network Automation with Python
Python network automation is becoming a must have skill in 2022. So you need to make sure you understand your objects, variables, methods, functions, dictionaries, strings, libraries 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. Network automation with Python is a skill that will be very beneficial for network engineers in 2022 and beyond. This list of Python automation scripts will be updated as and when I find or use another script. Anyone can learn Python! It’s even now part of the CCNA!
The best thing you can do is just start trying these scripts and getting hands on using Python. This is the best way to learn Python by getting a basic understanding of some simple scripts.
If you are new to Python you can check out my Python Tutorial for Beginners
Download all the scripts. Git clone the repository with this command:
git clone https://github.com/rogerperkin/python-scripts-for-network-engineers.git
Python for Network Automation
All the script examples below are focussed on automating Cisco routers but they will work equally well on switches and other devices. The scripts can be used and changed as you require and will work on most devices, they are only used here on CSR routers as a lab example. But they will also work on Juniper networks and most other vendors. You just need to change the command to match your target device.
Cisco Python Script Examples
We will work through with a step by step explanation from a simple script and then move up to more complex tasks.
1. Cisco Python script SSH to 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’ 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 Routers 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 you can connect to more devices and can run basic commands, the next step is to save that output. This Python script for backing up Cisco config is a great one to get you started.
One of the first tasks people usually take on when they get started is the 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'
# save backup in 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
Keep reading for more Cisco Python script examples.
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 the for loop.
This Python script example uses the devices.txt file again and loops 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 - Routers 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'
# save backup in 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.
Jinja2 is a templating language for Python developers. It is not just used by network engineers, it can be used to create files from templates for any code.
The basic setup is you create a template file that contains placeholders where you define a value i.e. DNS-Server then you have another file that contains these values and when you run your python script it picks the values and inserts them into your template and outputs a completed configuration file which you can push to your device.
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 for all you Python for Network Engineers
If you have any ideas for more sample Python scripts for network engineers please drop me a comment below.
Learning Python is not a quick task it is something network engineers need start doing daily. Start with the basics and you will become proficient.
If you want to consider other options check out my best network automation tools list
Topics to add:
netmiko, napalm, pyntc, telnet
Python Videos for Network Automation
You can also improve your understanding with python courses, but there are so many it’s difficult to know where to start. Check the extra resources below for starters.
Notes for development
Consider using pathlib when opening and writing files
https://docs.python.org/3.9/library/pathlib.html
More Python posts
Check out other content and resources I have written.
- Ansible vs Python
- Should network engineers learn Python?
- Pyats Genie Tutorial
- Python Virtual Environment Tutorial
- Nornir Training
- Ansible hosts file
Python course for network engineer
Python for Network Engineers Course
If you are looking for some Python courses for network engineers training to learn more about using Python to automate your network, I am currently creating an online course for network engineers, covering the Python programming language with a step by step explanation on how to use Python to mange your network, more info here: Python for Network Engineers Course
If you would like more information and would like to pre-register – send me an email Contact
Python Books for Network Engineers
Using Python for Network Engineers to automate the network is a skill that network engineers in 2022 need to learn. These are some of the books I would recommend to get in order of your current knowledge of Python.
- Mastering Python – https://www.amazon.com/gp/product/1449359361
- Network Automation & Programmability – https://www.amazon.com/gp/product/1491931256
- Mastering Python Networking – https://www.amazon.co.uk/Mastering-Python-Networking-automation-programmability/dp/1839214678
Network automation is no longer a nice to have it is an essential skill that every network engineer needs to know and a great place to start is with Python! There are so many Python modules that make it so easy to get started, even Cisco courses are now including Python as essential learning and with the Devnet certifications, it’s certainly here to stay.
Network engineers need to think of Python for Network Engineers as a standard skill and not a nice to have.
Learning Python has never been easier! Don’t know what data types are? Check out my other courses. It’s time to step away from the command line and embrace the Python modules!
In a later post I will be learning Python to automate software defined networking and also adding more courses to my network engineers training courses.
So I hope you can see the benefit of learning Python and how it can help you with automating your systems and make managing your infrastructure easier. Network administration is a breeze when you know Python and when you get going can really help with troubleshooting too!
Is Python good for network engineers?
As Python is a scripting language and runs through tasks in a sequential manner it’s a great language to automate complex network configurations. Cisco has adopted Python as their language of choice to automate network. Using Python, a network engineer can programmatically configure a network devices instead of manually typing the commands. It’s very quick and it’s easy to read syntax makes it the perfect programming language and is a critical skill for new network engineers. Every network engineer in 2022 needs to learn Python!
Coming Soon
Python Programming for Network Engineer
Python for Network Automation Projects
NAPALM (Network Automation and Programmability Abstraction Layer with Multivendor support)
Python for Network Engineers FAQ
Does a network engineer need coding skills?
In short, YES! If you want to make a career as a network engineer you are going to have to master coding to a certain level. Programming skills are becoming more of a core skill for network engineers today. With most devices exposing an API, if you want to learn to code. Python is a great place to start.
Does Cisco use Python?
Cisco have adopted Python as the preferred language for network engineers. The Cisco DevNet Associate exam tests experience with Python and other products i.e Meraki, Cisco ACI all expose an API with well documented Python scripting integration.
Should network engineers learn Python?
Yes, definitely! Python enables network engineers to build scripts to automate network configuration. It is the most commonly used programming language for network automation, and is a critical skill for network engineers today.
How do I learn Python for Networking?
There are a few courses available online to learn how to use Python for Networking. The main part is to be able to SSH to devices and the library to use for that is Netmiko, after that you might want to take a general Python course and then start looking at Nornir.
Is Python good for network engineers?
As Python is a scripting language and runs through tasks in a sequential manner it’s a great language to automate complex network configurations. Cisco has adopted Python as their language of choice to automate network. It’s very quick and it’s easy to read syntax makes it the perfect programming language and is a critical skill for new network engineers. Every network engineer in 2022 needs to learn Python!
Read more about Python Network Automation
Why Python for Network Engineers?
Python allows you to build scripts that will help you as a network engineer to automate small tasks and build up to an entire ecosystem that will manage your network. Network engineers need to start learning Python today.
I already use Ansible for network automation, so why should I bother learning Python?
Learning Python in addition to using Ansible for network automation is a powerful combination that can significantly enhance your capabilities in managing and automating network operations. While Ansible is a fantastic tool for automation, offering simplicity and the ability to get up and running quickly without writing code from scratch, Python adds depth and flexibility to your automation toolkit.
Why should network engineers should learn Python?
Network engineers should learn Python for several compelling reasons, which underscore Python’s relevance and utility in the evolving landscape of network engineering and automating networks.
Automation: Python simplifies the automation of repetitive and time-consuming tasks, such as configuration management, network device interrogation, and the deployment of changes across multiple devices. Automation increases efficiency, reduces human error, and allows network engineers to focus on more strategic tasks.
Wide Adoption and Community Support: Python is one of the most popular programming languages, with a vast community of developers. This community contributes to an extensive collection of libraries and frameworks that can significantly reduce the time and effort required to implement complex network automation tasks. The large community also means abundant resources, tutorials, and support forums, which are invaluable for learning and troubleshooting.
Versatility and Integration: Python’s versatility allows network engineers to use it for scripting, developing web applications, data analysis, and integrating network systems with other IT infrastructure. This capability is particularly important as networks become more integrated with cloud services, virtualization platforms, and other IT systems.
Network-Specific Libraries: Python boasts libraries specifically designed for network management and automation, such as Netmiko, NAPALM (Network Automation and Programmability Abstraction Layer with Multivendor support), and PySNMP. These libraries simplify interactions with network devices and protocols, making it easier to execute tasks like configuration changes, monitoring, and diagnostics.
Data Analysis and Visualization: Networks generate vast amounts of data that need to be analyzed and visualized for monitoring, performance optimization, and decision-making. Python, with libraries like Pandas, Matplotlib, and Seaborn, is a powerful tool for network data analysis, enabling engineers to extract insights and visualize network metrics effectively.
Development of Custom Tools and Solutions: Python allows network engineers to develop custom tools tailored to their specific needs, ranging from simple scripts to complex applications. This flexibility ensures that engineers can create solutions that perfectly fit their network’s unique requirements, enhancing productivity and efficiency.
Professional Development and Career Opportunities: Learning Python opens up significant professional development opportunities for network engineers. It enhances their skill set, making them more valuable to their current employer and more competitive in the job market. As networks become more software-defined and automation becomes a standard, the demand for network engineers proficient in Python is expected to grow.
Transition to DevOps and NetDevOps: The industry is moving towards a more integrated approach to development, operations, and network management, embodied in the DevOps and NetDevOps movements. Python skills are essential for network engineers looking to transition into these roles, as they involve the use of software development practices for network automation, orchestration, and operational tasks.
REMY
Hi, Roger. I see nothing listed underneath the “5. Config Generator using Jinja2”. Is it for future use? Thanks.
Roger Perkin
Hi Remy, yes – it’s a placeholder I need to finish the post!
Mountain Scott
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!
Roger Perkin
Yes, I have it on my list of jobs to do!
REMY
Awesome. Thanks for your prompt reply, Roger. Look forward to it.
Adam
Hi Roger,
If you get time can you show how to parse config back up files and check individual port config has specific commands applied and if it doesn’t write it to file with the port number that the command is missing from?
Roger Perkin
Sure, great use case – will add it to my list!
AC
I would like this as well. I’d also like it from global configuration perspective as well. Meaning the script should look to see if global and interface configurations are present and if not add those configurations. Thanks in advance
Roger Perkin
sure, I think this is a good use case and will look at building a script tonight
jag kang
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
Roger Perkin
Of course – use what you like!
Aamson
Thanks Roger !
Great post <3
pls add more
Roger Perkin
sure, there are more python scripts coming!
Jurdip
Hi Roger,
I used your backup script as it was just what I needed
I added the below module,
from datetime import datetime
updated the print statement
print (“Backing up ” + device + datetime.now().strftime(“%Y_%m_%d-%I_%M_%S_%p”))
and finally changed the filename to reflect the date so I can re-use this script and have history of older versions.
filename = device + datetime.now().strftime(“%Y_%m_%d-%I_%M_%S_%p”) + ‘.txt’
I will write a script to delete files after a certain period of time but thanks for taking the time to put these together
Roger Perkin
Thanks, I will update the post to include this – thanks!
Kenny
Hi Roger, are there Python scripts that automates the IT auditing of Cisco network devices? If you have to recommend One book only on using Python to learn network automation, which will it be?
Roger Perkin
Hi Kenny,
Take a look at pyATS it is a testing framework which I think is what you might be looking for?
If I were to recommend a book it would be this one as a general overview
https://www.amazon.co.uk/Network-Programmability-Automation-Next-Generation-Engineer/dp/1491931256
or this one to go a bit deeper
https://www.amazon.co.uk/Mastering-Python-Networking-automation-programmability/dp/1839214678
I am also currently reading this one
https://www.amazon.co.uk/Introducing-Python-Modern-Computing-Packages/dp/1492051365
Carsten Lymann
Nice and clean guide Roger.
Anyone new to automating networks, should look this way.
/ Carsten
Roger Perkin
Thanks Carsten, glad it helped!
Lukas Brian
Hey Roger, thanks for great post
quick question on section 2 SSH to multiple devices- how to proceed if we have different vendor devices and if we are extracting login details from external file [ .txt or .json]
Roger Perkin
Hi Lukas, this is where things get interesting. This Netmiko script uses the basic connectivity to just show the process, if you are going to use this for production and have different vendors and different login details you need to be looking at an automation framework to handle the inventory. Nornir and Anisble are two great tools for this and it just depends on your use case.