Python - 将 CSV 导入列表以用于 SSH/config 更改

Python - importing CSV into list to use for SSH/config changes

我的目标是能够通过 SSH 连接到大约 200 台路由器并更改配置。更改是基于位置的动态变化,因此我需要导入一个 CSV,它将 IP 映射到用于更改的文本(位置)。

现在它使用 "ipaddresses" 列表基于导入的 CSV 执行 SSH,但它随后输入 "facilities" 列表中的所有变量。我想它只使用 "ipaddresses" 列表中每个 IP 地址的 "facilities" 列表中的单个变量。我不确定我是否需要制作 table 或其他东西?任何帮助,将不胜感激。

import csv 
    from netmiko import ConnectHandler

    with open('NID3.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        ipaddresses = []
        facilities = []


        for row in readCSV:
            ipaddress = row[0]
            facility = row[1]

            facilities.append(facility)       
            ipaddresses.append(ipaddress)


    platform = 'cisco_ios'
    username = 'username'
    password = 'password'

    for host in ipaddresses:
        device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)

        config_commands = ['int gig0/1.7', 'description {0}'.format(facilities)]

        output = device.send_config_set(config_commands)
        print(output)
        print()
        output = device.send_command('show run int gig0/1.7')   
        print(output) 


        device.disconnect()

这种行为的原因是因为这一行。您基本上是在告诉它输出设施列表中的所有内容。

config_commands = ['int gig0/1.7', 'description {0}'.format(facilities)]

如果hosts和facilities的值相等,比如5个hosts对应5个facilities,你大概可以这样做。

import csv 
from netmiko import ConnectHandler  # Shouldn't be indented

# No difference where you're declaring this but by convention, it's easier to make changes to variable at the top than to look deep within the code
ipaddresses = []
facilities = []
platform = 'cisco_ios'
username = 'username'
password = 'password'

    with open('NID3.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')

        for row in readCSV:
            ipaddresses.append (row[0])
            facilities.append (row[1])

    # If there are the same number of IP address to facility
    for i in range (len (ipaddresses)):
        device = ConnectHandler(device_type=platform, ip=ipaddresses [i], username=username, password=password)

        config_commands = ['int gig0/1.7', 'description {0}'.format(facilities [i])]
        print (config_commands)  # Suggest to print config_commands to confirm this is what you wanted
        print (device.send_config_set(config_commands))
        print()
        print (device.send_command('show run int gig0/1.7'))

        device.disconnect()