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

How to loop over list of IP addresses, one per line in Python

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

我无法让它遍历一系列 IP 地址和 return 多个设备的命令输出。当我将多个 IP 添加到 .txt 列表时,出现脚本超时错误。这是通过两次添加相同的地址来证明的,所以我知道这些地址是好的,相比之下文件中只有一个地址并且它看起来毫无作用。

我正在寻找一种循环遍历 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()