使用Python解析LLDP输出

时间:2013-12-13 22:46:47

标签: python networking

lldpctl -f keyvalue以这种格式输出输出:

lldp.eth0.via=LLDP
lldp.eth0.rid=1
lldp.eth0.age=286 days, 06:58:09
lldp.eth0.chassis.mac=<removed>
lldp.eth0.chassis.name=<removed>
lldp.eth0.chassis.descr=Not received
lldp.eth0.port.ifname=Gi1/19
lldp.eth0.port.descr=GigabitEthernet1/19
lldp.eth0.port.auto-negotiation.supported=yes
lldp.eth0.port.auto-negotiation.enabled=yes
lldp.eth0.port.auto-negotiation.10Base-T.hd=yes
lldp.eth0.port.auto-negotiation.10Base-T.fd=yes
lldp.eth0.port.auto-negotiation.100Base-X.hd=no
lldp.eth0.port.auto-negotiation.100Base-X.fd=yes
lldp.eth0.port.auto-negotiation.1000Base-T.hd=yes
lldp.eth0.port.auto-negotiation.1000Base-T.fd=yes
lldp.eth0.port.auto-negotiation.current=1000BaseTFD - Four-pair Category 5 UTP, full duplex mode
lldp.eth0.vlan.vlan-id=<removed>
lldp.eth0.vlan.pvid=yes
lldp.eth1.via=LLDP
lldp.eth1.rid=2
lldp.eth1.age=286 days, 06:58:08
lldp.eth1.chassis.mac=<removed>
lldp.eth1.chassis.name=<removed>
lldp.eth1.chassis.descr=Not received
lldp.eth1.port.ifname=Gi1/19
lldp.eth1.port.descr=GigabitEthernet1/19
lldp.eth1.

我想使用Python将输出解析为这样的字典:

lldp['eth1']['port']['descr'] = 'GigabitEthernet1/19'

也考虑到这一点:

lldp['eth0']['rid'] = '1'

有没有一种可靠的方法可以使用python执行此操作,我有一个不可预测的深度来解析?

1 个答案:

答案 0 :(得分:4)

假设您在名为output的多行字符串中输出:

output_dict = {}
lldp_entries = output.split("\n")

for entry in lldp_entries:
    path, value = entry.strip().split("=", 1)
    path = path.split(".")
    path_components, final = path[:-1], path[-1]

    current_dict = output_dict
    for path_component in path_components:
        current_dict[path_component] = current_dict.get(path_component, {})
        current_dict = current_dict[path_component]
    current_dict[final] = value