1

这段代码几乎完美,但是第二个编号没有按预期工作。

user@linux:~$ cat ip.txt 
10.1.1.1
10.2.2.2
10.3.3.3
user@linux:~$

脚本.py

from netmiko import Netmiko

with open('ip.txt') as f:
    print('List of Hosts')
    print('-' * 13)
    for x,y in enumerate(f.read().split(), 1):
        print(f'{x} - {y}')
    f.seek(0)
    ip_list = f.read().splitlines()
    print('\nNo  Hostname \t IP Address')
    print('-' * 27)
    for ip in ip_list:
        net_connect = Netmiko(ip=ip, device_type='cisco_ios', username='u',password='p',secret='p')
        hostname = net_connect.find_prompt()[:-1]
        print(f'{x}    {hostname} \t  {ip}')

输出

user@linux:~$ python3 script.py 
List of Hosts
-------------
1 - 10.1.1.1
2 - 10.2.2.2
3 - 10.3.3.3

No  Hostname     IP Address
---------------------------
3    R1       10.1.1.1
3    R2       20.2.2.2
3    R3       30.3.3.3
user@linux:~$

期望的输出

user@linux:~$ python3 script.py 
List of Hosts
-------------
1 - 10.1.1.1
2 - 10.2.2.2
3 - 10.3.3.3

No  Hostname     IP Address
---------------------------
1    R1       10.1.1.1
2    R2       20.2.2.2
3    R3       30.3.3.3
user@linux:~$

更新:

with open('ip.txt') as f:
    print('List of Hosts')
    print('-' * 13)
    for x,y in enumerate(f.read().split(), 1):
        print(f'{x} - {y}')
    f.seek(0)
    ip_list = f.read().splitlines()
    print('\nNo  Hostname \t IP Address')
    print('-' * 27)
    for ip in ip_list:
        net_connect = Netmiko(ip=ip, device_type='cisco_ios', username='u',password='p',secret='p')
        hostname = net_connect.find_prompt()[:-1]
        for x, ip in enumerate(ip_list,1):
            print(f'{x}    {hostname} \t  {ip}')

输出:

user@linux:~$ python3 script.py 
List of Hosts
-------------
1 - 10.1.1.1
2 - 10.2.2.2
3 - 10.3.3.3

No  Hostname     IP Address
---------------------------
1    R1       10.1.1.1
2    R1       10.2.2.2
3    R1       10.3.3.3
1    R2       10.1.1.1
2    R2       10.2.2.2
3    R2       10.3.3.3
1    R3       10.1.1.1
2    R3       10.2.2.2
3    R3       10.3.3.3
user@linux:~$ 
4

1 回答 1

1

你没有x在第二个循环中设置,所以它只是使用第一个循环留下的最后一个值。

enumerate()就像在第一个循环中一样使用

    for x, ip in enumerate(ip_list):
        net_connect = Netmiko(ip=ip, device_type='cisco_ios', username='u',password='p',secret='p')
        hostname = net_connect.find_prompt()[:-1]
        print(f'{x}    {hostname} \t  {ip}')```
于 2020-04-20T15:53:42.823 回答