首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python只返回接口上的第一个IPv6地址

Python只返回接口上的第一个IPv6地址
EN

Stack Overflow用户
提问于 2018-09-26 15:25:10
回答 1查看 476关注 0票数 0

我试图使用CiscoConfParse在思科IOS配置,其中接口有更多的IPv6地址,我只得到第一个IP地址。代码,输入文件和输出下面我做错了什么?任何指导都很感激。

代码语言:javascript
复制
    confparse = CiscoConfParse("ipv6_ints.txt")

    # extract the interface name and description
    # first, we get all interface commands from the configuration
    interface_cmds = confparse.find_objects(r"^interface ")

    # iterate over the resulting IOSCfgLine objects
    for interface_cmd in interface_cmds:
        # get the interface name (remove the interface command from the configuration line)
        intf_name = interface_cmd.text[len("interface "):]
        result["interfaces"][intf_name] = {}

        IPv6_REGEX = (r"ipv6\saddress\s(\S+)")
        for cmd in interface_cmd.re_search_children(IPv6_REGEX):
           ipv6_addr = interface_cmd.re_match_iter_typed(IPv6_REGEX, result_type=IPv6Obj)
           result["interfaces"][intf_name].update({
              "ipv6": {
              "ipv6 address": ipv6_addr.compressed,
              }
            })

    print("\nEXTRACTED PARAMETERS\n")
    print(json.dumps(result, indent=4))

输入文件

EN

回答 1

Stack Overflow用户

发布于 2019-06-14 01:57:27

您说得对,re_match_iter_typed()只返回第一个匹配项,所以它不适合这个应用程序。

我建议一些类似的东西:

  • 像往常一样查找接口对象,使用find_objects()
  • 使用.children属性迭代接口对象的所有子对象
  • 对每个子对象使用re_match_typed() (默认值为默认值,这样您就可以很容易地检测到是否有IPv6地址匹配)。

下面的示例代码..。

代码语言:javascript
复制
import re

from ciscoconfparse.ccp_util import IPv6Obj
from ciscoconfparse import CiscoConfParse

CONFIG = """!
interface Vlan150
 no ip proxy-arp
 ipv6 address FE80:150::2 link-local
 ipv6 address 2A01:860:FE:1::1/64
 ipv6 enable
!
interface Vlan160
 no ip proxy-arp
 ipv6 address FE80:160::2 link-local
 ipv6 address 2A01:870:FE:1::1/64
 ipv6 enable
!"""

parse = CiscoConfParse(CONFIG.splitlines())

result = dict()
result['interfaces'] = dict()
for intf_obj in parse.find_objects(r'^interface'):
    intf_name = re.split(r'\s+', intf_obj.text)[-1]
    result['interfaces'][intf_name] = dict()

    IPV6_REGEX = r'ipv6\s+address\s+(\S+)'
    for val_obj in intf_obj.children:

        val = val_obj.re_match_typed(IPV6_REGEX, result_type=IPv6Obj,
            untyped_default=True, default='__not_addr__')
        if val!='__not_addr__':
            # Do whatever you like here...
            print("{} {}".format(intf_name, val.compressed))

运行此代码将导致:

代码语言:javascript
复制
$ python try.py
Vlan150 fe80:150::2/128
Vlan150 2a01:860:fe:1::1/64
Vlan160 fe80:160::2/128
Vlan160 2a01:870:fe:1::1/64
$

当然,您可以使用任何您想要的打包方案将这些结果打包到json中。

这种技术在获取Config值下的docs中得到了解释。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52521272

复制
相关文章

相似问题

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