You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:基于‘show port-channel summary’输出用Python动态构建端口通道映射字典的实现

交换机端口通道成员提取Python实现

实现思路

  • 过滤命令输出的冗余头部说明、空行、分隔线
  • 定位到含Group/Port-channel/Ports关键字的表头行后,按行识别两类内容:
    • 新端口通道行:特征为行开头是数字组号、后续带Po(或Port-channel)开头的端口通道名
    • 成员接口续行:开头无组号,仅包含物理接口名
  • 自动匹配当前行类型,归集成员接口到对应端口通道的列表中,原生支持接口跨行列排版

代码实现

import re

def extract_port_channel_members(show_output: str) -> dict:
    """
    从交换机show port-channel summary输出中提取端口通道与成员接口的映射
    :param show_output: 交换机命令返回的原始字符串
    :return: 键为端口通道名,值为成员接口列表的字典
    """
    # 按行分割,过滤空行
    lines = [line.strip() for line in show_output.splitlines() if line.strip()]
    
    # 定位表头行
    header_idx = 0
    for idx, line in enumerate(lines):
        if all(keyword in line for keyword in ['Group', 'Port-channel', 'Ports']):
            header_idx = idx
            break
    else:
        # 未找到表头直接返回空字典
        return {}
    
    # 预编译正则规则(可根据实际设备输出调整)
    # 匹配新端口通道行:开头为数字组号,后跟Po/Port-channel+数字的端口通道名
    po_line_re = re.compile(r'^(\d+)\s+((?:Po|Port-channel)\d+)\S+\s*(.*)$')
    # 匹配物理接口名(可扩展支持其他厂商接口前缀)
    interface_re = re.compile(r'((?:Gi|Eth|Te|Fo|Hu|Fa)\d+(?:/\d+)+)')
    
    po_mapping = {}
    current_po = None
    
    # 遍历数据行
    for line in lines[header_idx+1:]:
        # 跳过分隔线行
        if line.startswith(('-', '+')):
            continue
        
        # 匹配新端口通道行
        po_match = po_line_re.match(line)
        if po_match:
            current_po = po_match.group(2)
            po_mapping[current_po] = []
            interfaces = interface_re.findall(po_match.group(3))
            po_mapping[current_po].extend(interfaces)
        else:
            # 续行接口归集
            if current_po:
                interfaces = interface_re.findall(line)
                po_mapping[current_po].extend(interfaces)
    
    return po_mapping

# 测试用例
if __name__ == "__main__":
    sample_output = """Flags:  D - down        P - bundled in port-channel
            I - stand-alone s - suspended
            H - Hot-standby (LACP only)
            R - Layer3      S - Layer2
            U - in use      f - failed to allocate aggregator

            M - not in use, minimum links not met
            u - unsuitable for bundling
            w - waiting to be aggregated
            d - default port


    Number of channel-groups in use: 2
    Group  Port-channel  Protocol    Ports
    ------+-------------+-----------+-----------------------------------------------
    1      Po1(SU)        LACP      Gi0/1/0   Gi0/1/1
    2      Po2(RU)        -         Gi0/2/0   Gi0/2/1
                                                 Gi0/2/2  Gi0/2/3
    """
    result = extract_port_channel_members(sample_output)
    print(result)

适配调整说明

  • 兼容Po1、Port-channel1两种常见端口通道命名格式
  • 若设备接口前缀不在预设范围内(如华为GE/XGE),仅需修改interface_re的匹配前缀列表即可
  • 若命令输出状态标识位置有变化,可调整po_line_re的正则匹配规则

内容的提问来源于stack exchange,提问作者slowstack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.26 20:45:00