简体   繁体   English

Python - Netmiko 从 2 列读取

[英]Python - Netmiko read from 2 columns

I have the following code that reads a CSV with a list of hostnames, and runs 2 commands.我有以下代码读取带有主机名列表的 CSV,并运行 2 个命令。

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.我需要更改它,以便它收到的 CSV 文件有 2 列,一列包含主机名,另一列包含要插入该路由器的相应命令。

Hostname主机名 Comand命令
CPE_1111 CPE_1111 sh ip int br sh ip 国际br
CPE_2222 CPE_2222 sh run sh运行
etc 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

(...)

Your answer lies with how the csv is read.您的答案取决于如何读取 csv。 You can use csv.DictReader() to read each row and convert it to a dictionary.您可以使用csv.DictReader()读取每一行并将其转换为字典。

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 .然后在连接到每个路由器的for loop中,您可以 select 从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.不要忘记为要执行的disconnect() function 添加括号。

conn.disconnect()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM