2016-09-01 200 views
-1

我有下面的代碼,它將打開包含IP地址的.txt文件,然後連接到設備並捕獲命令輸出,然後將輸出打印到文件並聲明一切正常。如何循環遍歷IP地址列表,每行一列Python

我不能讓它通過一系列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() 

回答

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() 
+0

那麼,如果我在列表中有多個IP地址,我會返回一個錯誤,所以我可以看到它轉到.txt文件以獲得完美的IP地址。但只要我添加多個IP,它就會失敗。它不是IP問題,因爲當我更改IP時,它會收集所需的信息。 所以我想我的第二個問題是如何使這個循環遍歷列表,並選擇下一個IP每次。 –

+0

你能分享你收到的錯誤嗎? – harshil9968

+0

由於返回錯誤的長度而在編輯中共享 –