繁体   English   中英

使用Python解析LLDP输出

[英]Parse LLDP output with Python

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执行此操作,我有一个不可预测的深度来解析?

假设您在名为output的多行字符串中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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM