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

使用Python的ciscoconfparse检测Cisco IOS-XR邻居next-hop-self配置问题

解决IOS-XR配置中检测嵌套的next-hop-self问题

问题场景

我的IOS-XR配置如下:

router bgp 7
  bgp router-id 10.0.0.7
  address-family ipv4 unicast
  !
  neighbor 10.0.0.70
    remote-as 7
    update-source Loopback0
    route-policy MANGLE_IN in
    route-policy MANGLE_OUT out
      next-hop-self
  !
  neighbor 192.168.1.254
    remote-as 9
    route-policy EBGP_IN in
    route-policy EBGP_OUT out

我需要检测邻居10.0.0.70是否配置了next-hop-self,但使用以下Python代码返回空列表[],不符合预期:

from ciscoconfparse import CiscoConfParse

config = CiscoConfParse('config.txt')
result = config.find_parents_w_child('neighbor 10.0.0.70', 'next-hop-self')
print(result)

原因分析

find_parents_w_child方法默认只查找直接子节点,而配置里的next-hop-self是嵌套在route-policy MANGLE_OUT out命令下的二级子节点,不属于邻居节点的直接子项,因此无法被匹配到。

解决方案

需要先定位到邻居的配置节点,再递归查找该节点下所有层级的子节点中是否包含next-hop-self:

from ciscoconfparse import CiscoConfParse

config = CiscoConfParse('config.txt')
# 获取目标邻居的配置节点对象
neighbor_nodes = config.find_objects('neighbor 10.0.0.70')
if neighbor_nodes:
    # 递归查找该节点下所有包含next-hop-self的行
    match_lines = neighbor_nodes[0].re_search_children(r'next-hop-self')
    # 提取匹配到的文本内容
    print([line.text for line in match_lines])
else:
    print("未找到目标邻居配置")

运行这段代码后,会输出预期结果:[' next-hop-self']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:12:14