The Goal: Extract Values from CLI Output
You have a string. You need a specific value from somewhere inside it. Maybe the IP address on column 2, the status on column 5, or the uptime buried in a paragraph of text. These three tools , split(), indexing, and slicing , cover about 80% of real parsing work.
split() , Breaking a Line into Parts
Called with no arguments, .split() splits on any whitespace and removes empty strings. This is the default pattern for parsing tabular CLI output.
line = "GigabitEthernet0/0 10.0.0.1 YES NVRAM up up"
parts = line.split()
# ['GigabitEthernet0/0', '10.0.0.1', 'YES', 'NVRAM', 'up', 'up'] interface = parts[0] # 'GigabitEthernet0/0'
ip = parts[1] # '10.0.0.1'
status = parts[4] # 'up'
Pass a delimiter to split on a specific character: line.split("/") splits on slashes, line.split(":") on colons. This is useful for parsing CIDR notation or key:value pairs.
split(maxsplit=N) , When the Last Field Has Spaces
Some fields contain spaces , interface descriptions, hostnames, error messages. maxsplit tells Python to stop splitting after N splits, leaving the rest of the string intact as the last element.
line = "Serial0/0/0 unassigned YES unset up My WAN circuit to ISP"
parts = line.split(maxsplit=5)
description = parts[-1] # 'My WAN circuit to ISP'
Without maxsplit, the description would be split into individual words. maxsplit=5 gives you the first 5 tokens cleanly, and the rest goes into the last element.
Indexing , Grabbing One Character
Strings are sequences. Square brackets access individual characters by position, starting at 0.
s = "GigabitEthernet0/1" s[0] # 'G' , first character
s[-1] # '1' , last character
s[-3] # '0' , third from end
More useful in practice: indexing into a list that came from .split(). The character-by-character indexing matters when you're parsing fixed-width output where values always appear at a known column position.
Slicing , Extracting a Range
Slicing syntax is s[start:end]. The start index is included, end is excluded.
s = "10.0.0.1/24" s[0:7] # '10.0.0.' , characters 0 through 6
s[8:] # '24' , from index 8 to end
s[:7] # '10.0.0.' , from start to index 6
s[-2:] # '24' , last 2 characters # Split CIDR notation
ip_part = s.split("/")[0] # '10.0.0.1'
prefix_len = s.split("/")[1] # '24'
find() and index() , Locating a Substring
.find() returns the index (position) of the first occurrence of a substring. Returns -1 if not found. .index() does the same but raises a ValueError if not found , use it when absence means a bug, not a normal case.
line = "BGP state = Established, up for 2d03h" pos = line.find("up for")
if pos != -1: uptime = line[pos + 7:] # '2d03h'
partition() , When You Have a Separator
.partition(sep) splits into exactly three parts: everything before the first occurrence of sep, the separator itself, and everything after. It never raises an error.
line = "hostname = router-core-1"
before, sep, after = line.partition(" = ")
# before = 'hostname', sep = ' = ', after = 'router-core-1' key, _, value = line.partition(" = ")
print(key, value) # hostname router-core-1
This is cleaner than split(" = ", 1) for key=value parsing because it always returns 3 parts even if the separator is not found.
When to Reach for Regular Expressions
If the structure isn't consistent enough for split/slice/partition, use re.search(). Regular expressions are more powerful but also harder to read. Use them when simpler methods fail, not as the first tool.
import re line = "5 minute input rate 134000 bits/sec, 198 packets/sec"
match = re.search(r'(\d+) bits/sec', line)
if match: rate = match.group(1) # '134000'
Full Example: Parsing show version
import re
from netmiko import ConnectHandler device = {"device_type": "cisco_ios", "host": "10.0.0.1", "username": "admin", "password": "cisco123"} with ConnectHandler(**device) as conn: ver = conn.send_command("show version") # Extract hostname
for line in ver.splitlines(): if line.startswith("cisco") or "hostname" in line.lower(): hostname_line = line break # Extract IOS version
ver_match = re.search(r'Version (\S+),', ver)
ios_version = ver_match.group(1) if ver_match else "unknown" # Extract uptime
uptime_match = re.search(r'uptime is (.+)', ver)
uptime = uptime_match.group(1) if uptime_match else "unknown" print(f"IOS: {ios_version}, Uptime: {uptime}")
Watch the video
This topic has a full video on YouTube.
Comments (0)
Please sign in to comment.