Python: нумерация не работает должным образом - PullRequest
1 голос
/ 20 апреля 2020

Этот код почти идеален, однако вторая нумерация не работает должным образом.

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

script.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:~$ 

1 Ответ

2 голосов
/ 20 апреля 2020

Вы не устанавливаете x во втором l oop, поэтому он просто использует последнее значение, оставшееся от первого l oop.

Используйте enumerate() так же, как вы это делали в первый л oop

    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}')```
...