TextFSM

2.1.0 · active · verified Sat Apr 11

TextFSM is a Python module that implements a template-based state machine for parsing semi-structured text into Python tables. Originally developed by Google, it's widely used for extracting structured data from command-line interface (CLI) output of network devices. The library is currently at version 2.1.0 and has a sporadic but active release cadence, focusing on fixes and improvements.

Warnings

Install

Imports

Quickstart

This example demonstrates parsing a simple 'show ip interface brief' style output using an in-memory TextFSM template. It defines values to capture, a 'Start' state to match the header, and a rule to capture data lines into records.

import textfsm
import io

# Example template string (equivalent to a .textfsm file)
template_string = '''
Value Interface (\S+)
Value IP_Address (\S+)
Value Status (\S+)
Value Protocol (\S+)

Start
  ^Interface\s+IP-Address\s+Status\s+Protocol\s*$$
  ^${Interface}\s+${IP_Address}\s+${Status}\s+${Protocol} -> Record
'''

# Example raw text output to parse
raw_text_data = '''
Interface        IP-Address   Status     Protocol
GigabitEthernet0/1 192.168.1.1  up         up
GigabitEthernet0/2 10.0.0.1     up         up
Loopback0          unassigned   up         down
'''

# Open the template (using io.StringIO for a string, normally a file path)
with io.StringIO(template_string) as template_file:
    # Create a TextFSM object
    fsm = textfsm.TextFSM(template_file)

    # Parse the raw text data
    parsed_data = fsm.ParseText(raw_text_data)

    # Print headers and data
    print(fsm.header)
    for row in parsed_data:
        print(row)

# Expected output:
# ['Interface', 'IP_Address', 'Status', 'Protocol']
# ['GigabitEthernet0/1', '192.168.1.1', 'up', 'up']
# ['GigabitEthernet0/2', '10.0.0.1', 'up', 'up']
# ['Loopback0', 'unassigned', 'up', 'down']

view raw JSON →