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

Python实现路由器配置转嵌套字典的技术求助

路由器配置文件转指定嵌套字典的Python实现指导

我正在学习Python,需要把路由器配置文件interface.txt转换成指定结构的嵌套字典。目前已经实现了基础字典结构,但卡在两个关键点:区分主/secondary IP、生成vrfs前缀的嵌套逻辑处理。后续打算用ipaddress模块处理VRF列表中的IP,求技术指导。


附interface.txt示例

interface Bundle-Ether10023.1622
 description Workstations
 vrf r1320
 ipv4 address 10.10.10.1 255.255.255.0
 ipv4 address 10.10.20.1 255.255.255.0 secondary
 ipv4 address 10.10.30.1 255.255.255.0 secondary
 ipv4 address 10.10.40.1 255.255.255.0 secondary
interface Bundle-Ether10023.1618
 description AV_Mgmt
 vrf r1580
 ipv4 address 10.11.10.1 255.255.255.0

目标嵌套字典结构

{
    "ifcs": {
        "interfaceBundleEther10023_1622": {
            "description": "Workstations",
            "vrf": "r1320",
            "gws": {
                "primary": {
                    "10.10.10.1": "255.255.255.0"
                },
                "secondary": {
                    "10.10.20.1": "255.255.255.0",
                    "10.10.30.1": "255.255.255.0",
                    "10.10.40.1": "255.255.255.0"
                }
            },
            "vrfs": {
                "prefix": [
                    "10.10.10.0 255.255.255.0",
                    "10.10.20.0 255.255.255.0",
                    "10.10.30.0 255.255.255.0",
                    "10.10.40.0 255.255.255.0"
                ]
            }
        },
        "interfaceBundleEther10023_1618": {
            "description": "AV_Mgmt",
            "vrf": "r1580",
            "gws": {
                "primary": {
                    "10.11.10.1": "255.255.255.0"
                },
                "secondary": {
                    "null": "null"
                }
            },
            "vrfs": {
                "prefix": [
                    "10.11.10.0 255.255.255.0"
                ]
            }
        }
    }
}

当前已实现的基础结构

interfaceBundles = {
    "interface Bundle-Etherxxxx.": {
        "description": "xxxx",
        "vrf": "xxx",
        "ipv4 address": "xxxx xxxx"
    },
    "interface Bundle-Etherxxxx": {   
        "description": "xxxx",
        "vrf": "xxx",
        "ipv4 address": "xxxx xxxx"
    }
}

核心解决思路与实现代码

1. 区分主/secondary IP逻辑

读取配置时逐行解析:

  • 识别ipv4 address行,拆分字段后判断是否包含secondary关键字
  • 无关键字的IP归入gws下的primary字典,有则归入secondary字典

2. 用ipaddress生成VRF前缀

利用ipaddress.IPv4Interface类自动计算网络地址:

  • 将IP和子网掩码组合为ip/mask格式传入类构造器
  • 直接提取网络地址和子网掩码字符串,拼接成目标前缀格式

完整实现代码

import ipaddress
import json

def parse_interface_config(file_path):
    cfg = {"ifcs": {}}
    current_iface = None
    
    with open(file_path, 'r') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            
            # 初始化新接口的字典结构
            if line.startswith("interface"):
                iface_name = line.replace(" ", "").replace(".", "_")
                current_iface = {
                    "description": "",
                    "vrf": "",
                    "gws": {"primary": {}, "secondary": {}},
                    "vrfs": {"prefix": []}
                }
                cfg["ifcs"][iface_name] = current_iface
            
            elif current_iface is not None:
                # 处理描述信息
                if line.startswith("description"):
                    current_iface["description"] = line.split(" ", 1)[1]
                # 处理VRF配置
                elif line.startswith("vrf"):
                    current_iface["vrf"] = line.split(" ", 1)[1]
                # 处理IPv4地址
                elif line.startswith("ipv4 address"):
                    parts = line.split()
                    ip_addr = parts[2]
                    subnet_mask = parts[3]
                    is_secondary = len(parts) == 5 and parts[4] == "secondary"
                    
                    # 按主备分类存入gws
                    if is_secondary:
                        current_iface["gws"]["secondary"][ip_addr] = subnet_mask
                    else:
                        current_iface["gws"]["primary"][ip_addr] = subnet_mask
                    
                    # 生成VRF前缀并添加到列表
                    try:
                        ipv4_iface = ipaddress.IPv4Interface(f"{ip_addr}/{subnet_mask}")
                        prefix = f"{ipv4_iface.network.network_address} {ipv4_iface.netmask}"
                        current_iface["vrfs"]["prefix"].append(prefix)
                    except ValueError as err:
                        print(f"无效的IP/掩码组合 {ip_addr}/{subnet_mask}: {err}")
        
        # 给无secondary IP的接口补全null值
        for iface_data in cfg["ifcs"].values():
            if not iface_data["gws"]["secondary"]:
                iface_data["gws"]["secondary"] = {"null": "null"}
    
    return cfg

# 调用示例
if __name__ == "__main__":
    result = parse_interface_config("interface.txt")
    print(json.dumps(result, indent=4, ensure_ascii=False))

代码说明

  • 逐行读取配置文件,识别接口起始行后初始化对应嵌套字典
  • 分类型处理描述、VRF、IP地址,自动区分主备IP
  • 通过ipaddress模块准确计算网络前缀,避免手动计算出错
  • 最后统一处理无secondary IP的接口,补全要求的null结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 09:58:23