Parsing network device output with regular expressions

When automating network devices with Python, it’s common to need to parse the output of commands executed on the devices. Regular expressions provide a powerful and flexible way to extract data from the output of commands.

Here’s an example of using regular expressions to parse the output of a “show interfaces” command on a Cisco IOS router:

import re
from netmiko import ConnectHandler

device = {
    'device_type': 'cisco_ios',
    'ip': '',
    'username': 'admin',
    'password': 'password'

connection = ConnectHandler(**device)
output = connection.send_command('show interfaces')

# Define a regular expression pattern to match interface data
pattern = r"(\S+)\s+is\s+(up|down),\s+line protocol is\s+(up|down)"

# Use the findall function to extract interface data from the output
interfaces = re.findall(pattern, output)

# Print the interface data
for interface in interfaces:
    print("Interface: {}".format(interface[0]))
    print("Status: {}".format(interface[1]))
    print("Line protocol: {}".format(interface[2]))

In this example, we import the re module for regular expressions and the ConnectHandler class from the netmiko library. We connect to a Cisco IOS router and execute the show interfaces command. We then define a regular expression pattern to match interface data in the output of the command. We use the findall function to extract all instances of the pattern in the output.

The resulting interfaces variable is a list of tuples, with each tuple containing the interface name, status, and line protocol. We then iterate over the interfaces list and print the data for each interface.

Regular expressions can be used to extract data from a wide variety of network device commands. By using regular expressions, you can automate the process of parsing device output and extract the data you need for your network automation tasks.

Leave a Reply