首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >由"show port-channel summary“构建的python字典

由"show port-channel summary“构建的python字典
EN

Stack Overflow用户
提问于 2021-04-05 03:33:18
回答 1查看 19关注 0票数 0

我需要python代码的帮助,以便从"show port-channel summary“的输出中动态构建字典。以下是示例输出和字典。

代码语言:javascript
复制
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)   

需要构建字典:

代码语言:javascript
复制
{
    "Po1": [Eth1/2,Eth1/3,Eth2/3,Eth3/3],
    "Po2": [Eth2/2,Eth2/5],
    "Po201": [Eth1/4,Eth1/21]

}

你能用python代码来帮助实现这一点吗?

EN

回答 1

Stack Overflow用户

发布于 2021-04-05 03:56:29

您可以使用re模块来解析文本:

代码语言:javascript
复制
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)

打印:

代码语言:javascript
复制
{'Po1': ['Eth1/2', 'Eth1/3', 'Eth2/3', 'Eth3/3'], 'Po2': ['Eth2/2', 'Eth2/5'], 'Po201': ['Eth1/1']}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66945137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档