【问题标题】:How to loop over list of IP addresses, one per line in Python如何遍历IP地址列表,在Python中每行一个
【发布时间】:2016-09-01 10:16:30
【问题描述】:

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

我无法让它遍历一系列 IP 地址并返回多个设备的命令输出。当我将多个 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()

【问题讨论】:

    标签: python python-3.x cisco cisco-ios


    【解决方案1】:

    请记住,每一行都是一个新的 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 地址有问题
    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多