I have a RegEx that extracts Juniper router and interface names from RANCID configs. I want to properly utilize a dict
, set
or list
(doesn't honestly matter, I display a dict
in my example) that will store the router names from my example text (the dict
key
) without duplicates (ONE router name per device). Then add each interface found from the RegEx to the correct router name that the interface belongs to.
-- Example of what I how I'd like to store the data: dict of lists maybe? --
'router1.test.com': ['ae10.100']
'pe9-router.test.com': ['xe-0/0/4', 'xe-0/0/4.0', 'ae10.100']
-- My example text I am working with: --
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
"""
-- CODE SO FAR --
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)]
-- ipython3 output of the above code ---
In [67]: rancid_filename_match_list
Out[67]:
[('router1.test.com', 'ae10.100'),
('switch9.test.com', 'xe-0/0/4'),
('switch9.test.com', 'xe-0/0/4.0'),
('switch9.test.com', 'ae10.100')]
As my ipython3 output shows it isn't working how I'd like it to. I hope someone can lend some help please.
I've tried many different ways of getting my idea into code, but I can never get the router names to not duplicate - unless I use a python set
, but when I use a set
I cannot figure out how to add the interface names specifically to the only router that they should belong to.
You can use dictionary where keys are the hostnames and values are lists with interfaces:
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
"""
out = {}
for k, v in re.findall(r"(\S+):# (\S+)", text):
out.setdefault(k, []).append(v)
print(out)
Prints:
{
"router1.test.com": ["ae10.100"],
"pe9-router.test.com": ["xe-0/0/4", "xe-0/0/4.0", "ae10.100"],
}