Parsing indented config blocks

Read a router configuration

Lesson 19 of 20 · 12 min · Module 6: Policies and audits

Routers and switches store their configuration as text. Turning it into data lets you check hundreds of devices automatically.

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…

  • Parse a block-structured text format
  • Track state while reading lines
  • Convert masks to prefix lengths

The idea

In this Cisco-style format, interface NAME starts a block and indented lines below it describe that interface: description …, ip address ADDRESS MASK, and shutdown (disabled). A line starting with ! is a separator. ipaddress.IPv4Network("0.0.0.0/" + mask).prefixlen turns a mask into a prefix length.

import ipaddress
print(ipaddress.IPv4Network("0.0.0.0/255.255.255.252").prefixlen)

01Indentation shows ownership

Indented lines belong to the last unindented line above them. Remember the interface you are inside and attach every indented setting to it.

02State machines are simple

current is either None (outside an interface) or the dict being filled. Each line either starts a new interface, adds to the current one, or ends the block.

03Masks to prefixes

Configs often store masks such as 255.255.255.252. IPv4Network("0.0.0.0/255.255.255.252").prefixlen gives 30, so you can store the modern CIDR form.

import ipaddress
print(ipaddress.IPv4Network("0.0.0.0/255.255.255.0").prefixlen)
Output
24

Your turn

Write parse_interfaces(config) that returns a dict mapping each interface name to {"description": text or None, "address": "ADDRESS/PREFIX" or None, "enabled": bool}. An interface is enabled unless its block contains shutdown. Ignore lines outside interface blocks.

What the checks look for

  • Parses description, address and state
  • Detects shutdown interfaces
  • Uses None for missing description and address
  • Ignores lines outside interface blocks
Try it in the editor →

Take this with you

Read configs line by line, tracking which block you are in.

Go a little further

Collect the hostname from the hostname line and return it alongside the interfaces.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →