Python Forum

Full Version: Batch network configuration/ verification task using Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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

See the code below and also here: http://afifi.name/batch-network-configuration-python/

def main():
    import csv
    import datetime
    import sys
    from netmiko import ConnectHandler

    with 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)
do you have a question or this is completed script you want to share in which case it should be posted in Completed scripts section? If the later I will move it for you.