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

Python网络自动化脚本:根据接口名获取Juniper路由实例名称

问题描述

我正在编写Python网络自动化脚本,遇到了无法解决的问题。已从Juniper设备获取路由实例输出如下:

CPE-MGT {
    instance-type virtual-router;
    interface ge-0/0/0.0;
    routing-options {
        static {
            route 192.168.253.115/32 next-hop 192.168.100.1;
            route 0.0.0.0/0 next-hop 192.168.100.1;
        }
    }
}
DATA {
    instance-type virtual-router;
    interface ge-0/0/1.0;
}
MGMT_BK {
    instance-type virtual-router;
    interface ge-0/0/2.0;
    routing-options {
        static {
            route 192.168.253.115/32 next-hop 192.168.100.1;
            route 0.0.0.0/0 next-hop 192.168.100.1;
        }
    }
}

我需要根据指定接口名获取对应的路由实例名称,例如找到ge-0/0/0.0时,获取其所属的CPE-MGT。目前我能通过正则匹配到接口,但不知道如何获取对应的路由实例名称,现有代码如下:

cmd = net_connect.send_command(
        juniper_cmds["sh_routing_instance"])
    logger.debug(f'{ip_dict[config_dict["csv_ip_colum"]][ips]}:Device routing instances {cmd}')
    regex_routing_instance = re.compile(f'{interface[0]}')
    routing_instance = regex_routing_instance.findall(cmd)

解决方案

以下两种方法均可实现需求:

方法1:改进正则表达式匹配

利用正则的跨行匹配特性,先定位路由实例名称,再匹配目标接口:

import re

target_interface = "ge-0/0/0.0"
# 构建正则模式,匹配路由实例名 + 后续内容中包含目标接口的片段
pattern = re.compile(
    r'(\w+)\s+\{.*?interface\s+' + re.escape(target_interface) + r';',
    re.DOTALL
)
match_result = pattern.search(cmd)

if match_result:
    instance_name = match_result.group(1)
    print(f"接口{target_interface}所属路由实例:{instance_name}")
else:
    print(f"未找到接口{target_interface}对应的路由实例")
  • re.DOTALL允许.匹配换行符,确保跨多行匹配完整的路由实例块
  • re.escape()处理接口名中的特殊字符,避免干扰正则逻辑
  • 非贪婪匹配.*?确保只匹配到最近的路由实例,不会跨实例匹配

方法2:逐段解析文本结构

将输出按路由实例分割后,逐个检查每个实例中的接口:

target_interface = "ge-0/0/0.0"
# 按"}"分割路由实例,过滤空内容并补全闭合符
instance_blocks = [block + "}" for block in cmd.split("}") if block.strip()]

for block in instance_blocks:
    if f"interface {target_interface};" in block:
        # 提取第一行的路由实例名称
        instance_name = block.split("{")[0].strip()
        print(f"接口{target_interface}所属路由实例:{instance_name}")
        break
else:
    print(f"未找到接口{target_interface}对应的路由实例")

这种方法逻辑直观,无需复杂正则,适合结构固定的设备输出。


内容的提问来源于stack exchange,提问作者Walter Joel Solano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 22:00:29