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

时间:2016-09-01 10:16:31

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

我有以下代码,它将打开包含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()

1 个答案:

答案 0 :(得分:0)

请记住,每一行都是新的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()