Parse a saved configuration with a defined grammar
Read a small teaching configuration format while preserving quoted descriptions and invalid-line evidence.
Begin with a format you can describe
This course uses a deliberately small teaching format, not a vendor command language. The first meaningful line is device <name>. Later lines describe an interface, one VLAN, administrative state and a quoted description in a fixed order. Blank lines and comments are allowed.
Use shlex.split with POSIX parsing and comments enabled. It keeps a quoted description containing spaces or a # character together while treating an unquoted # as a comment. Splitting on whitespace alone would lose that distinction. An unfinished quote is an invalid line.
A parser should retain useful evidence
The device header establishes which export you are reading, so a missing or invalid header fails the whole input. After a valid header, malformed interface lines become error records and parsing continues. Record physical line numbers, including any earlier blank or comment lines.
Normalize identifiers, validate the VLAN range defined for this format, and keep the first valid occurrence of an interface. A later duplicate is an error, even if its settings differ. Sort accepted interfaces for a stable report, while errors remain in input order.
Configuration text stays data. shlex tokenization does not execute a shell, and this function never sends the parsed lines to a network device. A real vendor configuration requires its own documented grammar and adapter.
import shlex
line = 'interface wan0 vlan 10 admin up description "Café # uplink" # note'
print(shlex.split(line, comments=True))
Put it into practice.
Define parse_config(text) for the supplied teaching grammar. First nonblank/noncomment line: device <name>. Require device matching [a-z0-9][a-z0-9-]* after strip().casefold(); missing/invalid header raises ValueError. Each later meaningful line must have exactly eight shlex tokens: interface <name> vlan <id> admin <up|down> description <text>. Normalize interface names; require [a-z0-9][a-z0-9/.-]*. VLAN is ASCII decimal 1..4094. Preserve description text, including an empty quoted description. Use shlex POSIX comments. Invalid lines become {line, reason:"invalid record"}; later valid duplicate names become "duplicate interface". Return device, interfaces (interface, vlan, admin, description sorted by interface), errors (physical line order).
See an explained solution
import shlex, re
def parse_config(text):
device, ports, errors, seen = None, [], [], set()
for number, line in enumerate(text.splitlines(), 1):
try:
tokens = shlex.split(line, comments=True, posix=True)
except ValueError:
if device is None:
raise ValueError("Invalid device header")
errors.append({"line":number,"reason":"invalid record"})
continue
if not tokens:
continue
if device is None:
if len(tokens) != 2 or tokens[0] != "device" or not re.fullmatch(r"[a-z0-9][a-z0-9-]*",tokens[1].strip().casefold()):
raise ValueError("Expected device header")
device = tokens[1].strip().casefold()
continue
valid = len(tokens) == 8 and tokens[0] == "interface" and tokens[2] == "vlan" and tokens[4] == "admin" and tokens[6] == "description"
if valid:
name = tokens[1].strip().casefold()
valid = bool(re.fullmatch(r"[a-z0-9][a-z0-9/.-]*",name)) and tokens[3].isascii() and tokens[3].isdecimal() and 1 <= int(tokens[3]) <= 4094 and tokens[5] in ("up","down")
if not valid:
errors.append({"line":number,"reason":"invalid record"})
elif name in seen:
errors.append({"line":number,"reason":"duplicate interface"})
else:
seen.add(name)
ports.append({"interface":name,"vlan":int(tokens[3]),"admin":tokens[5],"description":tokens[7]})
if device is None:
raise ValueError("Missing device header")
return {"device":device,"interfaces":sorted(ports,key=lambda row:row["interface"]),"errors":errors}
if __name__ == "__main__":
from pathlib import Path
print(parse_config(Path("edge.conf").read_text(encoding="utf-8")))
The parser distinguishes grammar, identity and policy validation. Quoted descriptions remain intact, and invalid lines cannot silently overwrite a prior valid interface.