• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

Roger Perkin

Learn Network Automation

  • AWS
  • Network Automation Training
    • Ansible Workshop
    • What is Network Automation?
    • Network Automation Tools
    • Ansible Training
      • What is Ansible?
      • Ansible Tutorial for Beginners
      • Ansible Network Automation
      • Ansible Hosts File
    • Python Network Automation
      • Nornir Training
      • Python Network Automation Course
      • Python for Network Engineers
      • Python VENV / Virtual Environment Tutorial
      • Python Tutorial for Beginners
      • pyATS
    • Network Source of Truth
    • DevOps Tutorial
      • Git Training
      • Terraform Training
      • Linux Training
      • Kubernetes Training
      • Devops Training Course
      • Azure Devops Training
    • Terraform
    • GIT
      • Git Commands
    • Docker
    • Confluence
    • Microsoft Azure
  • Cisco
    • ISE
    • SD WAN Training
    • Password Recovery
    • Software-Upgrade-Guides
    • BGP
    • Data Center
    • WIRELESS
  • CCIE
  • Blog
  • About
    • My Red Special Guitar
  • Contact
python code hero image

Python for Network Engineers

Home » Network Automation » Python Network Automation

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.

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.

ansible network automation course

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!

python for network engineers
python-for-network-engineers

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!

ssh-to-multiple-routers.py

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.

backup-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)

#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.

backup-multiple-routers.py

# 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 Course for Network Engineers

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

[email protected]

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!

Frequently asked questions

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.

Category: Python Network Automation
ansible course for network engineers
Get Access to my Ansible Course NOW
Previous Post:python virtual environment tutorial venvPython VENV / Virtual Environment Tutorial
Next Post:What is Computational Thinking?

Reader Interactions

Comments

  1. REMY

    November 29, 2020 at 1:02 pm

    Hi, Roger. I see nothing listed underneath the “5. Config Generator using Jinja2”. Is it for future use? Thanks.

    Reply
    • Roger Perkin

      November 29, 2020 at 3:03 pm

      Hi Remy, yes – it’s a placeholder I need to finish the post!

      Reply
      • Mountain Scott

        January 12, 2021 at 6:12 am

        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!

        Reply
        • Roger Perkin

          January 22, 2021 at 12:20 pm

          Yes, I have it on my list of jobs to do!

          Reply
  2. REMY

    November 29, 2020 at 3:15 pm

    Awesome. Thanks for your prompt reply, Roger. Look forward to it.

    Reply
    • Adam

      August 8, 2021 at 2:37 am

      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?

      Reply
      • Roger Perkin

        August 17, 2021 at 4:23 pm

        Sure, great use case – will add it to my list!

        Reply
      • AC

        January 17, 2022 at 2:56 am

        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

        Reply
        • Roger Perkin

          January 23, 2022 at 11:33 am

          sure, I think this is a good use case and will look at building a script tonight

          Reply
  3. jag kang

    January 21, 2021 at 9:24 pm

    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

    Reply
    • Roger Perkin

      January 22, 2021 at 12:20 pm

      Of course – use what you like!

      Reply
  4. Aamson

    March 27, 2021 at 8:10 am

    Thanks Roger !
    Great post <3

    pls add more

    Reply
    • Roger Perkin

      April 6, 2021 at 1:11 pm

      sure, there are more python scripts coming!

      Reply
  5. Jurdip

    April 12, 2021 at 2:39 am

    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

    Reply
    • Roger Perkin

      April 12, 2021 at 11:35 pm

      Thanks, I will update the post to include this – thanks!

      Reply
  6. Kenny

    April 25, 2021 at 9:49 am

    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?

    Reply
    • Roger Perkin

      April 27, 2021 at 12:45 pm

      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

      Reply
  7. Carsten Lymann

    September 10, 2021 at 7:37 am

    Nice and clean guide Roger.

    Anyone new to automating networks, should look this way.

    / Carsten

    Reply
    • Roger Perkin

      September 13, 2021 at 11:13 am

      Thanks Carsten, glad it helped!

      Reply
  8. Lukas Brian

    January 23, 2022 at 11:30 am

    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]

    Reply
    • Roger Perkin

      January 23, 2022 at 11:35 am

      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.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Sidebar

Hi I'm Roger Perkin,
Based in the UK working as a Network Devops Engineer, CCIE #50038
About Roger | Twitter | Linkedin

More Python

  • Python Network Automation
  • pyATS Tutorial for Beginners
  • Network Automation Certification
  • Python for Network Engineers
  • Python VENV / Virtual Environment Tutorial

Recent Posts

  • Ansible AWX
  • Ansible Variable Precedence
  • Ansible Lightspeed
  • Three Modern-Day Business Technology Must-Haves
  • Azure Data Lake

Topics

Network Automation
Ansible
Python for Network Automation
CCIE
Cisco ISE
F5 Certification
BGP
OSPF
Pluralsight Trial
auvik promo banner

Git for Network Engineers

Ansible vs Nornir

Start learning today with my Network Automation Courses

Master Ansible, Python, Git, Nornir, Jenkins and more..


Buy me a coffeeBuy me a coffee

network automation course

Have you seen my YouTube Channel?

YouTube Subscribe

Let’s get started

Take a look at my premium courses on Ansible, Nornir & Git or buy them all with the Network Automation Bundle!

Network Automation Courses

Navigation

Home

Blog

About

Contact

Network Automation

Network Tools

Python VENV Tutorial

Python for Network Engineers

Ansible Training
Devops Tutorial
DIY Garden Office

Contact

Get in touch with me here

[email protected]

  • Facebook
  • Instagram
  • Twitter
  • LinkedIn
  • YouTube
Buy me a coffeeBuy me a coffee

YouTube

Don’t forget to take a look at my YouTube Channel

youtube button

Tech

Best Vertical Mouse for RSI

Copyright © 2023 · Roger Perkin · All Rights Reserved · Privacy Policy – Terms