Network Automation using Python Programming

  • By
  • July 29, 2019
  • Network Automation
Network Automation using Python Programming

Networking Future:

Picture1

Nowadays Network programmability is an advanced trend in the IT industry. It is enhanced and inspired by new network automation technology i.e. Software Defined Networks(SDN) and DevNet, that are based on scripting methods and standard programming languages like Python is used for controlling, monitoring and troubleshooting of network elements. I am illustrating some advance methods for networking devices configurations by using network automation, reducing time for equipment configuration and easier maintenance. One of the most important advantages of this technique is that we can also improve network security by recognizing and fixing security vulnerabilities and it increases the network stability. These methods represent the future of networks and network engineers as well. This trend is allowing the management of an increased number of devices in a unitary way.

WHY PYTHON FOR NETWORKING ENGINEERS?

Picture2

Python has top of the charts in recent years over other programming languages like C, C++ and Java and is widely used by the programmers. 

The software development and networking companies prefer Python language because of its versatile features and fewer programming codes. Nearly 15% of the programmers use it on the operating systems like UNIX, Linux, Windows and Mac OS. 

Features of Python: 

The Network programmers use Python as it has created a mark for itself in the configuration script with characteristic features like-

Picture12

Python programming language can be used to automate manual tasks by writing simple scripts. It is a convenient tool for the server and networking devices for managing tasks and configurations. Python is also used for interacting with SDN (Software Defined Networking), managing multiple networking devices and utilizing APIs. The Python interpreter helps the network engineer to make his own scripts to manage the routine tasks and easily configure networking assets within an organization. You will only need a few lines of commands within a configuration script rather than the long lines of code. This is why network engineering interested more for Python. It’s simple, easy to learn and less complex compared to languages like Java or Ruby. Python also can be used on devices which provides real-time monitoring.

But the question is remain same “Why use Python for network programming instead of Other programming Languages?” If that is the case, these are valid reasons: Python has some really good and advance libraries that make network programming easier and make a script for multiple networking devices. Common libraries are Paramiko And Netmiko.

Benefits of Python for Network automation:

The Python language has diversified application in software development and networking companies. This provides the language a higher priority over other programming languages used in the industry. Some of its advantages are-

Extensive Support Libraries: It provides a large range of standard python libraries that covers different types of domain. Most of the commonly used programming tasks are already scripted into it that limits the length of the codes to be written in Python.

Integration Feature: Python integrates the different types of Enterprise Application Integration that makes it easy to develop different services for different applications. It has powerful control capabilities as it calls directly through C, C++ or Java and other programming languages as well  via Python. Python also use to configure XML and other markup languages as it can run on all modern operating systems through same byte code.

Improved Programmer’s Productivity: The language has clean object-oriented designs and extensive support libraries that increase programmer’s productivity. 

Productivity: With its strong process with integration features, enhanced control capabilities and unit testing framework contribute the role in  increasing speed for most applications and productivity of applications. It is a great option for building scalable, reliable and multi-protocol network applications.

Network Automation using Python :

The number of devices in a network and their heterogeneous nature and configuration complexity is steadily increasing. The traditional methods for configuring these devices based on CLI mode and using some automation tools. These methods are time-consuming, taking into consideration also the vendor-specific know-how needed. The Software Defined Networks (SDN) concept tries to eliminate the vendor dependency via standard protocols. 

However, the “traditional” non-SDN based networks need to keep the speed of configuration and respond to dynamic network changes. That is really hard to manage with manual network configuration technique. Network automation is a solution for Operational Expenses OPEX saving(OPEX is an ongoing cost for running a product, business, or system.), improving not only the time spent for configuring the network devices but it is also efficient for network maintenance through procedures that are easier to follow and implement at large scale. 

Picture19

Network programmability using DevNet allows for reliable and dynamic infrastructure configurations by automating deployments using python programming language, simplifying the network and reducing human-generated errors.

All major vendors in the networking domain, including Cisco, started promoting the software configurability of networks with python programming ability (e.g. Cisco DevNet concept that promotes the creation of an open-source community for network programmability). All new automation implementations are based on generic programming methods (python, java) and standard interfaces (Secure Shell SSH or even REST API  ).

The main objective of this blog is to demonstrate the efficiency of the scripting in configuring network devices. For that we have created a network topology using GNS3 emulated tool, having as main element a Docker Container Ubuntu image, with the role of a network controlling element. We have controlled the network devices in a programmatic way using the Netmiko and Paramiko open-source packages, based on Python.

 

Video Will Help a Lot!

Python modules for network automation: Netmiko and Paramiko

At its core, network programmability and automation has the main goal of simplifying the tasks involved in configuring, managing and operating network equipment, network topologies, network services and network connectivity. In our experimental setup we have used the GNS3 emulator which is a tool for building, designing and testing networks, capable now also to connect to external networks and allowing integration with virtual images or Docker Containers. 

Both Netmiko and Paramiko modules are using SSH connection to get the control of devices. SSH (Secure Shell) is a cryptographic (encryption and decryption) network protocol work on 22 port number for operating network services securely over an unsecured network. Encryption is a process of conversion of human-readable data into human unreadable format i.e. called Ciphertext. Decryption is an inverse process of Encryption in which we are converting Ciphertext into plain text means normal human-readable text format.

For Free Demo classes Call: 7798058777

Registration Link: Click Here!

Paramiko is a Python implementation of the SSHv2 protocol, providing both client and server functionality. It is a pure Python interface around SSH networking concepts and it allows cryptographic functionality to secure network connections. 

Netmiko libraries support multi-vendors, based on Paramiko, simplifying connections across a broad set of networking vendors and platforms. The scripts incorporate various functionalities like VLAN creation, routing protocols or configuration backup. We can use these scripts for almost all network devices regardless of the vendor that produces them. 

A. Network setup

For our specific implementation, we have used an Ubuntu Docker Container which is running Python scripts, allowing to connect to devices and automate their configuration via ssh connections. Python scripting is based on Netmiko and Paramiko libraries for controlling the network devices. 

We use four Layer 3 Switches and two Layer 2 Switches (using real Cisco IOS) that is making the connection to the NAT Cloud (for having access to the Internet) and these switches are already done with basic configuration.

Capture

Topology Diagram

The Ubuntu Operating System Docker Container needs to be in the same network as the devices that we want to we can configure a static IP address or automatically configure so it can obtain an IP address via a common DHCP server. It also must be connected to the Internet for downloading the necessary libraries.

Necessary libraries and packages for Ubuntu Docker container

apt-get update

apt-get install python -y

apt-get install build-essential libssl-dev libffi-dev -y

apt-get install python-pip -y

pip install cryptography

pip install paramiko

pip install netmiko

pip install –upgrade pip

Basic configuration on L3 switches

  1. Configured Hostname : Switch1, Switch2 ……  Switch4
  2. Username : 7m
  3. Password : 7m 
  4. Enable Password : ccna
  5. Ip address : 192.168.122.11-14 255.255.255.0 (on interface e0/0)
  6. Configured SSH using 7m Domain name with 1024 RSA algorithm key

Basic configuration on L2 switches

  1. Configured Hostname : Switch5, Switch6 
  2. Username : 7m
  3. Password : 7m 
  4. Enable Password : ccna
  5. Ip address : 192.168.122.15-16 255.255.255.0 (on vlan 1)
  6. Configured Telnet

B. Basic Python automation method

With the help of Netmiko and Paramiko, we can write simple scripts for networking devices configurations.  But understanding paramiko and netmiko module, first of all, we need to understand the basic telnet library and it’s working. So in given below script i am trying to show you how to create multiple vlans and assigns name for that vlans on those two Layer 2 Switches. 

In Topology diagram total 6 Devices with layer 3 and layer 2 switches are configured. we can see the script used to create multiple vlans on multiple switches. We already have to specify the IP address configured on the switches, the username and the password configured. 

In Example 1 We have written script in a such a way that when the connection is established successful, we have created a loop that creates VLANs from 2 to 10 (VLAN 1 is configured implicitly on every switch) on switch5 and switch6 using telnet lib module.

Example 1: Basic vlan configuration Scripts

import getpass

import sys

import telnetlib

for i in range(15,17):

        HOST = “192.168.122.”+str(i)

        tn = telnetlib.Telnet(HOST)

        tn.read_until(“Username: “)

        tn.write(“7m” + “\n”)

        tn.read_until(“Password: “)

        tn.write(“7m” + “\n”)

        tn.write(“en\n”)

        tn.write(“ccna\n”)

        tn.write(“conf t\n”)

        for j in range(2,10):

                tn.write(“vlan ” +str(j) + “\n”)

                tn.write(“name ” “vlan_”+str(j) + “\n”)

        tn.write(“end\n”)

        tn.write(“exit\n”)

        print (tn.read_all())

Example 2 is a another basic script for networking device configuration in which we are taking backup of L3 switches using file content as an argument for ip address. After successful connection, this script take a backup of L3 switches within a minute.

For Free Demo classes Call: 7798058777

Registration Link: Click Here!

Example 2: Basic Backup script

#!/usr/bin/env python

import getpass

import telnetlib

#Ask for username and password

user=raw_input(“Enter your telnet username: “)

password=getpass.getpass()

#Open a file called switch_list

f=open(‘switch_list’)

#Telnet to switches and get the running config

for line in f:

        print “Getting Backup from switch” +(line)

#strip for removing empty space

        HOST = line.strip()

        tn = telnetlib.Telnet(HOST)

        tn.read_until(“Username: “)

        tn.write(user + “\n”)

        tn.read_until(“Password: “)

        tn.write(password + “\n”)

        tn.write(“en\n”)

        tn.write(“ccna\n”)

        tn.write(“terminal length 0\n”)

        tn.write(“sh clock \n”)

        tn.write(“sh run \n”)

        tn.write(“exit\n”)

        readoutput=tn.read_all()

        saveoutput=open(“switch”+HOST,”w”)

        saveoutput.write(readoutput)

        saveoutput.close()

 Note: Switch_list file contain IP address of the devices

192.168.122.11

192.168.122.12

192.168.122.13

192.168.122.14

For Free Demo classes Call: 7798058777

Registration Link: Click Here!

C. Python automation using Paramiko Module 

As we can see, the Netmiko and Paramiko is the advance module for networking device configuration. Paramiko module uses an easier way to connect to switches using ConnectHandler which is also using SSH in the backend. With the script from Example 3, we can create a loopback interface  on multiple switches. 

Example 3: Paramiko example 

import paramiko

import getpass

import time

ip_add=raw_input(“Please Enter IP address of the device: “)

user_name=raw_input(“Enter device username: “)

password=getpass.getpass()

loopback=raw_input(“Please Enter loopback number:”)

ssh_client=paramiko.SSHClient()

ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh_client.connect(hostname=ip_add,username=user_name,password=password)

print “Successful connection”, ip_add

#rc=Remote_conncetion

rc=ssh_client.invoke_shell()

rc.send(“en \n”)

rc.send(“ccna\n”)

rc.send(“config t \n”)

rc.send(“int loopback ” +str(loopback) + “\n\n” )

rc.send(“ip add  1.1.2.1 255.255.255.0 \n”)

rc.send(“end \n”)

time.sleep(1)

ouput=rc.recv(65535)

print “Loopback is configure successfully”

ssh_client.close

Below we present another script using Netmiko that can create VLANs on a number of switches, available in the topology.

D. Python automation using Netmiko Module 

As we can see, the difference between Paramiko and Netmiko is that Netmiko module is used in an easier way to connect to switches using ConnectHandler which is also using SSH in the backend. In addition, when we use Netmiko we have to specify the device type that we want to configure using the script. With the script from Example 4, we can take a backup of multiple switches. The main difference between Example 4 script and Example 3 is that in Example4 script uses a variable (all_devices) which includes all the other four switches in this case. Afterward, same like in the previous script, we have used a loop that is useful for collecting backup from all L3 Switches.

Example 4 implements a simple functionality, suitable for exemplification purposes, but the configuration possibilities are broad. We consider the two above mentioned Python implementations as a good alternative and less dependent on vendor-specific commands compared to the “expect” method of TCL scripting language, very much used by network administrators for automation. 

With the help of Netmiko and Paramiko, we have written a script that takes backups of multiple L3 Switches as shown in the topology diagram. 

For Free Demo classes Call: 7798058777

Registration Link: Click Here!

Example 4: Backup using Netmiko 

#!/usr/bin/env python

import getpass

import telnetlib

import time

from netmiko import ConnectHandler

time1=time.time()

Switch1 = {

    ‘device_type’: ‘cisco_ios’,

    ‘ip’: ‘192.168.122.11’,

    ‘username’: ‘7m’,

    ‘password’: ‘7m’, 

    ‘secret’ : ‘ccna’,

    ‘global_delay_factor’: 2,

 }

Switch2 = {

    ‘device_type’: ‘cisco_ios’,

    ‘ip’: ‘192.168.122.12’,

    ‘username’: ‘7m’,

    ‘password’: ‘7m’, 

    ‘secret’ : ‘ccna’,

    ‘global_delay_factor’: 2,

 }

Switch3 = {

    ‘device_type’: ‘cisco_ios’,

    ‘ip’: ‘192.168.122.13’,

    ‘username’: ‘7m’,

    ‘password’: ‘7m’, 

    ‘secret’ : ‘ccna’,

    ‘global_delay_factor’: 2,

 }

Switch4 = {

    ‘device_type’: ‘cisco_ios’,

    ‘ip’: ‘192.168.122.14’,

    ‘username’: ‘7m’,

    ‘password’: ‘7m’, 

    ‘secret’ : ‘ccna’,

    ‘global_delay_factor’: 2,

 }

router_list=[Switch1, Switch2, Switch3, Switch4]

name_list=[‘Switch1′,’Switch2′,’Switch3′,’Switch4’]

name_list1=[‘Switch1.txt’,’Switch2.txt’,’Switch3.txt’,’Switch4.txt’]

count=0

for device in router_list:

    net_connect = ConnectHandler(**device)

    out= net_connect.find_prompt()

    print(out)

    out1=str(out)

    out=net_connect.enable()

    out2= net_connect.find_prompt()

    print (“Collecting backup from device: ” +str(name_list[count]))

    #outp=net_connect.send_command(“terminal length 0”)

    net_connect.send_command(“en”)

    net_connect.send_command(“ccna”)

    output1 = net_connect.send_command(“show clock”,delay_factor=2)

    output2 = net_connect.send_command(“show run”,delay_factor=2)

    saveoutput=open((name_list1[count]),”w”)

    saveoutput.write(out2)

    saveoutput.write(‘show clock \n’)

    saveoutput.write(output1)

    saveoutput.write(‘\n\n’)

    saveoutput.write(out2)

    saveoutput.write(‘show run \n’)

    saveoutput.write(output2)

    saveoutput.write(‘\n’)

    saveoutput.write(out2)

    saveoutput.write(‘\n’)

    saveoutput.close()

    print (“Backup sucessfull for Device ” +str(name_list[count]))

    print (“\n”)

    count=count+1

time2=time.time()

print(“Total time taken for complete procedure : ” +str(time2-time1))

time.sleep(4)

Author Name: Onkar Kubade

Designation: Network Engineer

For Free Demo classes Call: 7798058777

Registration Link: Click Here!

Call the Trainer and Book your free demo Class for now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.

2 thoughts on “Network Automation using Python Programming

  1. Would like to Kno the fees structure

Submit Comment

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

*
*