循环访问IP地址列表

时间:2016-09-06 08:40:21

标签: python python-3.x cisco

我有下面的代码,它将在.txt文件中查找IP地址,然后转到设备并返回命令,然后打印到请求的文件,一切正常。

我不能做的是循环一系列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()

为清楚起见,下面给出的答案非常适合我的要求,所以代码的开头将如下所示:

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:
    host = host.strip()
    device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
    output = device.send_command('terminal length 0')

等等什么命令都需要运行。

1 个答案:

答案 0 :(得分:2)

我的猜测是,ConnectHandler并不意识到host字符串末尾有换行符。

试试这个:

for host in ip_add_file:
    host = host.strip()
    ...
相关问题