Notes on Networking

A blog to share my study notes on Cisco networking and more

Batch network configuration/ verification with Python.

Jul
02

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

The following header line and columns are mandatory in the inventory.txt CSV file and must be in compliance with netmiko:

hostname, ip, port, username, password, secret, device_type

import csv
import datetime
import sys
from netmiko import ConnectHandlerwith open("inventory.txt","r") as file_h:
    csv_reader = csv.reader(file_h,delimiter=",")
    header = csv_reader.next()
    inventory = []
    for raw in csv_reader:
        if len(raw) == len(header):
            dev_dic = {}
            for col in range(len(header)):
                dev_dic.update({header[col].strip():raw[col].strip()})
            inventory.append(dev_dic)lines = ""
with open("script.txt","r") as file_h:
    for line in file_h:
        lines = lines + line
script = lines.splitlines() log = ""
for device in inventory:
    dev_dic = {"ip":device["ip"],
        "port":device["port"],
        "username":device["username"],
        "password":device["password"],
        "secret":device["secret"],
        "device_type":device["device_type"]}
    try:
        output = " "
        connection_h = ConnectHandler(**dev_dic)
        connection_h.enable()
        #output = connection_h.send_config_set(script)
        for line in script:
            output = output + connection_h.send_command_expect(line) + "\n"
        output = output.replace("\n","\n ")
        timestamp = str(datetime.datetime.now())
        msg = timestamp + ", " + \
            "Hostname: " + device["hostname"] + ", " + \
            "IP: " + device["ip"] + ", " + \
            "Port: " + device["port"] + ", " + \
            "Successful!\n" + output + "\n"
        print(msg)
        log = log + msg
    except:
        error_message = str(sys.exc_info()[0])
        timestamp = str(datetime.datetime.now())
        msg = timestamp + ", " + \
            "Hostname: " + device["hostname"] + ", " + \
            "IP: " + device["ip"] + ", " + \
            "Port: " + device["port"] + ", " + \
            "Error!\n " + error_message + "\n"
        print(msg)
        log = log + msg
        pass
with open("log.txt","w") as file_h:
    file_h.write(log)

 

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

Share

Leave a Reply

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

%d bloggers like this: