Python Forum
Batch network configuration/ verification task using Python
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Batch network configuration/ verification task using Python
#1
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)
Reply
#2
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to connect over network and get the task done maiya 3 2,021 Jul-10-2022, 05:01 AM
Last Post: maiya
  Why Python for Network Programming ashilnayak2 1 2,476 May-18-2020, 09:20 AM
Last Post: DeaD_EyE
  Assistance with Python Network script cscecela 2 4,773 Feb-24-2019, 01:23 AM
Last Post: searching1
  A virtual network to use with python to learn about networking with python? marienbad 0 2,355 Feb-11-2019, 09:20 PM
Last Post: marienbad
  Python module for Router configuration parsing anna 0 3,640 Mar-08-2018, 06:02 PM
Last Post: anna
  How to direct python to use a specific network adapter? ormesome 9 10,929 Nov-08-2017, 06:42 PM
Last Post: nilamo
  Scapy route6 configuration peterkl 0 3,784 Mar-06-2017, 03:58 PM
Last Post: peterkl

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020