如何循环IP地址列表,Python中每行一个

如何循环IP地址列表,Python中每行一个,python,python-3.x,cisco,cisco-ios,Python,Python 3.x,Cisco,Cisco Ios,我有下面的代码,它将打开包含IP地址的.txt文件,然后连接到设备并捕获命令输出,然后将输出打印到文件并声明一切正常 我无法让它循环通过一系列IP地址并返回多个设备的命令输出。当我向.txt列表中添加多个IP时,脚本超时出错。这是通过添加两次相同的地址来证明的,因此我知道这些地址是好的,而不是当文件中只有一个地址并且它工作正常时 我正在寻找一种方法来循环10个IP地址并运行相同的命令: from __future__ import print_function from netmiko impo

我有下面的代码,它将打开包含IP地址的.txt文件,然后连接到设备并捕获命令输出,然后将输出打印到文件并声明一切正常

我无法让它循环通过一系列IP地址并返回多个设备的命令输出。当我向.txt列表中添加多个IP时,脚本超时出错。这是通过添加两次相同的地址来证明的,因此我知道这些地址是好的,而不是当文件中只有一个地址并且它工作正常时

我正在寻找一种方法来循环10个IP地址并运行相同的命令:

from __future__ import print_function
from netmiko import ConnectHandler

import sys
import time
import select
import paramiko
import re
fd = open(r'C:\Users\NewdayTest.txt','w') 
old_stdout = sys.stdout   
sys.stdout = fd 
platform = 'cisco_ios'
username = 'Username'
password = 'Password'

ip_add_file = open(r'C:\Users\\IPAddressList.txt','r') 

for host in ip_add_file:
    device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
    output = device.send_command('terminal length 0')
    output = device.send_command('enable')
    print('##############################################################\n')
    print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
    output = device.send_command('sh run')
    print(output)
    print('##############################################################\n')
    print('...................CISCO COMMAND SHOW IP INT BR OUTPUT......................\n')
    output = device.send_command('sh ip int br')
    print(output) 
    print('##############################################################\n')

fd.close()

请记住,每一行都将是一个新的IP地址

并且您不需要写入ciscoOutput文件,您可以使用命令
fd.write('text')
来实现这一点

from __future__ import print_function
from netmiko import ConnectHandler

import sys
import time
import select
import paramiko
import re
fd = open(r'C:\Users\LocationOfMyFile\CiscoOutput.txt','w') 
old_stdout = sys.stdout   
sys.stdout = fd 
platform = 'cisco_ios'
username = 'My Username'
password = 'My Password'

ip_add_file = open('file_name.txt','r') 

for host in ip_add_file:

    device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)


    output = device.send_command('show version')
    print(output)


    output = device.send_command('terminal length 0')
    print(output)


    output = device.send_command('sh ip int br')
    print(output)


    output = device.send_command('show interfaces GigabitEthernet0/1')
    print(output)

fd.close()

好吧,这是一个处理,但我返回一个错误,如果我有一个以上的IP地址在列表中,所以我可以看到它去的.txt文件,以获得IP地址,这是完美的。但一旦我添加了多个IP,它就会失败。这不是IP问题,因为当我更改IP时,它会收集所需的信息。因此,我想我的第二个问题是如何在列表中循环并每次选择下一个IP。由于返回的错误长度,在编辑下共享IP地址这是IP地址的一些问题,就像现在这样