Python - Netmiko 从 2 列读取

Python - Netmiko read from 2 columns

我有以下代码读取包含主机名列表的 CSV,并运行 2 个命令。

我需要对此进行更改,以便它接收到的 CSV 文件有 2 列,一列包含主机名,另一列包含要插入该路由器的相应命令。

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

(...)

您的答案在于如何读取 csv。您可以使用 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

然后在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"])

不要忘记为要执行的 disconnect() 函数添加括号。

conn.disconnect()