gpt4 book ai didi

python - 使用 Python 解析 LLDP 输出

转载 作者:太空宇宙 更新时间:2023-11-03 15:16:19 25 4
gpt4 key购买 nike

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_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

关于python - 使用 Python 解析 LLDP 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20577303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com