遍历列表并更新字典

时间:2019-07-31 21:59:33

标签: python-3.x dictionary

我需要创建一个字典以与另一个python库一起使用。 我有输入脚本的网络设备列表。我需要获取输入文件中所有设备的IP地址,并将其添加到字典中。

我的问题是,该dict仅使用输入文件中最后一个设备的IP更新。

import napalm
from napalm import get_network_driver
from collections import defaultdict

device_driver = get_network_driver('junos')

dev_dict = defaultdict(dict)

with open("devices.txt") as d:
    devices = d.readlines()

for line in devices:
    try:
        device = device_driver(line.rstrip('\n'),'username','password')
        device.open()
    except:
        print("Connection error!")
        continue

for line in devices:
    try:
        dev_dict[line.rstrip('\n')]['ipv4'] = device.get_interfaces_ip()['lo0.0']['ipv4']
    except:
        continue

print(dev_dict)
defaultdict(<class 'dict'>, {'device1': {'ipv4': {'10.1.1.1': {'prefix_length': 32}}}, 'device2': {'ipv4': {'10.1.1.1': {'prefix_length': 32}}}})

因此,有两个设备正在循环通过。 该字典最终看起来像:

dev_dict
defaultdict(dict,
            {'device1': {'ipv4': {'10.1.1.1': {'prefix_length': 32}}},
             'device2': {'ipv4': {'10.1.1.1': {'prefix_length': 32}}}})

注意IP地址如何相同? device2应该不同(10.1.1.2)

$cat devices.txt
device1
device2

我在这里想念什么?

2 个答案:

答案 0 :(得分:0)

我猜是因为您已经对接口“ lo0.0”进行了硬编码

“ dev_dict [line.rstrip('\ n')] = device.get_interfaces_ip()['lo0.0'] ['ipv4']”

您看到的IP地址是lo0.0的接口

答案 1 :(得分:0)

尝试一下

import napalm
from napalm import get_network_driver
from collections import defaultdict

device_driver = get_network_driver('junos')

dev_dict = defaultdict(dict)

with open("devices.txt") as d:
    devices = d.readlines()

for line in devices:
    try:
        device = device_driver(line.rstrip('\n'),'username','password')
        device.open()
        dev_dict[line.rstrip('\n')]['ipv4'] = device.get_interfaces_ip()['lo0.0']['ipv4']
    except:
        print("Connection error!")
        continue

这应该有效。