我正在尝试在Cisco IOS配置上使用CiscoConfParse,其中接口具有多个IPv6地址,而我仅获得第一个IP地址。下面的代码,输入文件和输出我在做什么错?任何指导表示赞赏。
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))
输入文件
答案 0 :(得分:0)
您是正确的,re_match_iter_typed()
仅返回第一个匹配项,因此不适合该应用程序。
我建议遵循以下原则:
find_objects()
.children
属性遍历接口对象的所有子对象re_match_typed()
(具有默认值,以便您可以轻松检测到IPv6地址是否匹配)。下面的示例代码...
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))
运行此代码会导致:
$ 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中。
该技术在文档中Get Config Values下进行了解释