我需要python代码的帮助,以便从"show port-channel summary“的输出中动态构建字典。以下是示例输出和字典。
switch# show port-channel summary
Flags: D - Down P - Up in port-channel (members)
I - Individual H - Hot-standby (LACP only)
s - Suspended r - Module-removed
b - BFD Session Wait
S - Switched R - Routed
U - Up (port-channel)
M - Not in use. Min-links not met
--------------------------------------------------------------------------------
Group Port- Type Protocol Member Ports
Channel
--------------------------------------------------------------------------------
1 Po1(SU) Eth LACP Eth1/2(P) Eth1/3(P) Eth2/3(P)
Eth3/3(P)
2 Po2(RU) Eth LACP Eth2/2(P) Eth2/5(P)
201 Po201(RD) Eth LACP Eth1/1(P) 需要构建字典:
{
"Po1": [Eth1/2,Eth1/3,Eth2/3,Eth3/3],
"Po2": [Eth2/2,Eth2/5],
"Po201": [Eth1/4,Eth1/21]
}你能用python代码来帮助实现这一点吗?
发布于 2021-04-05 03:56:29
您可以使用re模块来解析文本:
import re
txt = """
switch# show port-channel summary
Flags: D - Down P - Up in port-channel (members)
I - Individual H - Hot-standby (LACP only)
s - Suspended r - Module-removed
b - BFD Session Wait
S - Switched R - Routed
U - Up (port-channel)
M - Not in use. Min-links not met
--------------------------------------------------------------------------------
Group Port- Type Protocol Member Ports
Channel
--------------------------------------------------------------------------------
1 Po1(SU) Eth LACP Eth1/2(P) Eth1/3(P) Eth2/3(P)
Eth3/3(P)
2 Po2(RU) Eth LACP Eth2/2(P) Eth2/5(P)
201 Po201(RD) Eth LACP Eth1/1(P)
"""
r_line = re.compile(r"^(\d+.*?\n)(?=\d+|\Z)", flags=re.S | re.M)
data = {}
for line in r_line.findall(txt):
_, k, _, _, v = line.split(maxsplit=4)
data[k.split("(")[0]] = [i.split("(")[0] for i in v.split()]
print(data)打印:
{'Po1': ['Eth1/2', 'Eth1/3', 'Eth2/3', 'Eth3/3'], 'Po2': ['Eth2/2', 'Eth2/5'], 'Po201': ['Eth1/1']}https://stackoverflow.com/questions/66945137
复制相似问题