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

2024-04-25 13:44:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 文件import命令iptxtsendoutputdevice
1条回答
网友
1楼 · 发布于 2024-04-25 13:44:32

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

相关问题 更多 >