如何将正则匹配的Juniper路由器与接口存入无重复字典
从RANCID配置提取Juniper路由器与接口并整理为字典
需求说明
需要从RANCID配置文本中提取Juniper路由器名称和对应的接口信息,最终用字典存储:
- 路由器名称作为字典的key,且不重复
- 每个key对应一个列表,存储该路由器下的所有接口
期望存储格式示例:
{ 'router1.test.com': ['ae10.100'], 'pe9-router.test.com': ['xe-0/0/4', 'xe-0/0/4.0', 'ae10.100'] }
现有代码与问题
示例文本
text = """ router1.test.com:# ae10.100 up up CKT/112233//ID Myname pe9-router.test.com:# xe-0/0/4 up down CKT2/332211//ID - Myname pe9-router.test.com:# xe-0/0/4.0 up down CKT/112233//ID - Myname pe9-router.test.com:# ae10.100 up down CKT/112233//ID - Myname """
正则匹配代码
import re findme_rancid_juniper_regex = re.compile( r"(?P<rancid_files>^.*?):#\s*(?P<juniper_ifaces>[gxel][et]-[0-9]*/[0-9]*/[0-9]*\.?[0-9]*|ae[0-9]*\.[0-9]*)", re.IGNORECASE | re.MULTILINE) rancid_filename_match_list = [m.groups() for m in findme_rancid_juniper_regex.finditer(text)]
当前运行输出
[('router1.test.com', 'ae10.100'), ('pe9-router.test.com', 'xe-0/0/4'), ('pe9-router.test.com', 'xe-0/0/4.0'), ('pe9-router.test.com', 'ae10.100')]
当前代码仅能提取出路由器与接口的元组列表,无法直接整理为需求的字典结构。
解决方案
在现有匹配结果的基础上,遍历元组列表并构建目标字典,同时可按需添加接口去重逻辑。
实现代码
import re text = """ router1.test.com:# ae10.100 up up CKT/112233//ID Myname pe9-router.test.com:# xe-0/0/4 up down CKT2/332211//ID - Myname pe9-router.test.com:# xe-0/0/4.0 up down CKT/112233//ID - Myname pe9-router.test.com:# ae10.100 up down CKT/112233//ID - Myname """ findme_rancid_juniper_regex = re.compile( r"(?P<rancid_files>^.*?):#\s*(?P<juniper_ifaces>[gxel][et]-[0-9]*/[0-9]*/[0-9]*\.?[0-9]*|ae[0-9]*\.[0-9]*)", re.IGNORECASE | re.MULTILINE) # 初始化空字典存储结果 router_interfaces = {} for match in findme_rancid_juniper_regex.finditer(text): router = match.group('rancid_files') iface = match.group('juniper_ifaces') # 若路由器未在字典中,创建对应空列表 if router not in router_interfaces: router_interfaces[router] = [] # 可选:避免同一接口重复添加 if iface not in router_interfaces[router]: router_interfaces[router].append(iface) print(router_interfaces)
运行结果
{ 'router1.test.com': ['ae10.100'], 'pe9-router.test.com': ['xe-0/0/4', 'xe-0/0/4.0', 'ae10.100'] }
逻辑说明
- 遍历每个正则匹配结果,分别提取路由器名和接口信息
- 检查路由器是否已存在于字典中,不存在则初始化对应的空列表
- 可选添加接口去重判断,避免同一接口被重复存储(适用于原始文本可能出现重复接口的场景)
内容的提问来源于stack exchange,提问作者agent dale cooper
相关产品推荐
相关产品推荐

