re.search, named groups & device facts
Pull facts out of show version
Lesson 6 of 20 · 14 min · Module 2: Read the network
Some outputs are not tables: show version is a page of text. Regular expressions pick out the few facts you need, such as the model, the software version and the serial number.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Find a fact in free text with re.search
- Name the part you want with a named group
- Handle a pattern that does not match
The idea
re.search(pattern, text) returns the first match, or None. A named group (?P<serial>\S+) captures part of the match, and match["serial"] reads it. \S+ means a run of characters that are not spaces, and .+ means the rest of the line. Write patterns against the line that holds the fact, for example System serial number\s+: (?P<serial>\S+).
import re
line = ("Cisco IOS Software, C2960L Software (C2960L-UNIVERSALK9-M), "
"Version 15.2(7)E8, RELEASE SOFTWARE (fc3)")
match = re.search(r"Version (?P<version>[^,]+),", line)
print(match["version"])
01Search, then read the group
re.search scans the whole text and stops at the first match. The named group holds just the value.
import re
import os
from netmiko import ConnectHandler
USERNAME = os.environ["NET_USERNAME"]
PASSWORD = os.environ["NET_PASSWORD"]
device = {"device_type": "cisco_ios", "host": "10.0.0.1",
"username": USERNAME, "password": PASSWORD}
with ConnectHandler(**device) as conn:
text = conn.send_command("show version")
match = re.search(r"System serial number\s+: (?P<serial>\S+)", text)
print(match["serial"])FOC2248Y1QZ02Rest of the line
.+ runs to the end of the line, because . does not match a newline. That is exactly what the uptime needs.
print(re.search(r"uptime is (?P<uptime>.+)", text)["uptime"])13 weeks, 0 days, 4 hours, 18 minutes03No match gives None
Not every device prints every line. Check the match before reading a group, or the script stops with an error.
match = re.search(r"Huawei Versatile Routing Platform", text)
print(match)
print(match["serial"] if match else "not found")None
not foundYour turn
facts(output) for the text of Cisco show version. It returns a dictionary with model (WS-C3560CX-8PC-S), version (15.2(7)E8), serial (the system serial number) and uptime (the text after uptime is). Run it on core1 and sw2 and store the results in inventory_facts, keyed by device name.What the checks look for
- core1 facts are right
- sw2 facts are right
- facts works on any show version
- Ran show version on both switches
Take this with you
Use one small pattern per fact, with a named group for the value.
Go a little further
Also read the number of Gigabit Ethernet interfaces ("12 Gigabit Ethernet interfaces") as an integer.