Batch network configuration/ verification with Python.

This simple Python code reads a configuration/ commands file (script.txt) and a CSV formatted inventory file (inventory.csv) and then apply the configuration/ commands to the devices in the inventory file and finally generates a simple output file (output.txt).

Here is the CSV formatted inventory file:

ip,hostname,type,category,folder,username,password,telnet_port,ssh_port,netconf_port
192.168.240.201,IOSXRv-1,cisco_ios,csr,default,automation,P@ssw0rd,23,22,830
192.168.240.202,IOSXRv-2,cisco_ios,csr,default,automation,P@ssw0rd,23,22,830

And this is the Python script:

import csv
from netmiko import ConnectHandler
import sys

devices = []
response = ""

with open("inventory.csv", "r") as file_h:
    for record in csv.DictReader(file_h):
        devices.append(record)

with open("script.txt", "r") as file_h:
    script = file_h.readlines()

for device in devices:
    response = response + \
               "{HOSTNAME}[{IP}]:\n".format(HOSTNAME=device["hostname"],IP=device["ip"])
    try:
        with ConnectHandler(ip=device["ip"],
                            port=device["ssh_port"],
                            username=device["username"],
                            password=device["password"],
                            device_type=device["type"]) as connect_h:

            for line in script:
                response = response + connect_h.send_command_expect(line) + "\n\n"
                
    except:
        response = response + str(sys.exc_info()[0])

with open("output.txt", "w") as file_h:
    file_h.write(response)

Read more about network automation here:

Network Programmability and Automation: Skills for the Next-Generation Network Engineer

Read more about netmiko here: https://github.com/ktbyers/netmiko

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.