pythonnetmiko

Python - Netmiko read from 2 columns


I have the following code that reads a CSV with a list of hostnames, and runs 2 commands.

I need to change this so that the CSV file it receives has 2 columns, one with the hostname, and another with the corresponding command to be inserted in that router.

Hostname Comand
CPE_1111 sh ip int br
CPE_2222 sh run
etc (...)
(...)

nodenum=1
f=open('routers.csv', 'r') #File with Hostnames
c=f.read()
file_as_list = c.splitlines()


with open('Output.txt','w') as f: #File with output
    
    logf = open("error.csv", "a") #Logfile
    loga = csv.writer(logf)
    loga.writerow(["Hostname"])

    for i in file_as_list :
        print ("Node", nodenum, "...Checking IP Address...", i)
        try:
            Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios" , username=raw_input("Enter your Username:"), password=getpass.getpass(), verbose=False)
        except:
            try:
                print("Cannot connect via SSH. Trying Telnet")
                Connection = netmiko.ConnectHandler(ip=i, device_type="cisco_ios_telnet" , username=raw_input("Enter your Username:"), password=getpass.getpass(), verbose=False)
                
            except:
                    print("SSH and Telnet Failed")
                    print("")
                    now = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                    loga.writerow([i])
                    nodenum = nodenum+1
                    continue
          
        hostname = (Connection.send_command("show run | include hostname"))
        cellular = (Connection.send_command("sh ip int brief"))
        Connection.disconnect

(...)

Solution

  • Your answer lies with how the csv is read. You can use csv.DictReader() to read each row and convert it to a dictionary.

    import csv
    
    with open(file="routers.csv", mode="rt") as f:
        next(f)
        lst = csv.DictReader(f=f, fieldnames=["ip", "cmd"])
        ips_cmds = list(lst)
    
    for ip_cmd in ips_cmds:
        print("Hostname:", ip_cmd["ip"])
        print("Command:", ip_cmd["cmd"], end="\n\n")
    
    # Hostname: CPE_1111
    # Command: show ip interface brief
    
    # Hostname: CPE_2222
    # Command: show running-config
    

    Then in the for loop where you connect to each router, you can select the value you need from the keys specified in fieldnames.

    conn = ConnectHandler(
        device_type="cisco_ios",
        ip=ip_cmd["ip"],
        username=input("Username: "),
        password=getpass(prompt="Password: "),
        secret=getpass(prompt="Enable Secret: "),
        fast_cli=False,
    )
    
    
    hostname = conn.send_command(command_string=ip_cmd["cmd"])
    

    Don't forget to add the parentheses for disconnect() function to be executed.

    conn.disconnect()