使用Python解析LLDP输出

4

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方法,可以在我需要解析的深度不可预测的情况下完成此操作?


像这样的吗?http://stackoverflow.com/questions/20386727/how-to-parse-and-print-a-tree-in-python/20388111#20388111 - PasteBT
1个回答

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

这很完美。谢谢! - andyhky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接