In this lesson, we will cover:
- What is TextFSM?
- How to install Scrapli TextFSM.
- Scrapli TextFSM with the NTC template library.
- Scrapli TextFSM with custom templates.
You can find the scripts and code for this lesson within the Scrapli repo under the directory: 002_scrapli_core/006_parsing/textfsm/.
What is TextFSM?
TextFSM is a Python module developed by Google that allows you to take unstructured data and convert it to structured data via sets of regex-based templates. An example of a TextFSM template for parsing the output of show_version
on an EOS is shown below:
Value MODEL (\S+)
Value HW_VERSION (\S+)
Value SERIAL_NUMBER (\S+)
Value SYS_MAC (\S+)
Value IMAGE (\S+)
Value TOTAL_MEMORY (\d+)
Value FREE_MEMORY (\d+)
Start
^Arista\s+${MODEL}
^Hardware\s+version:\s+${HW_VERSION}
^Serial\s+number:\s+${SERIAL_NUMBER}
^System\s+MAC\s+address:\s+${SYS_MAC}
^Software\s+image\s+version:\s+${IMAGE}
^Total\s+memory:\s+${TOTAL_MEMORY}
^Free\s+memory:\s+${FREE_MEMORY} -> Record
Installation
To perform Scrapli TextFSM parsing, first you must install the optional extra TextFSM package:
pip3 install "scrapli[textfsm]"
Note: If you have previously installed the hands-on lab environment, this dependency will have already been installed.
NTC Template Library
First, we will use Scrapli to parse our output by using the existing NTC TextFSM library. This library can be found at https://github.com/networktocode/ntc-templates and contains various parsers for a range of different vendor and platform types.
To instruct Scrapli to parse the response through the corresponding NTC TextFSM parsing template, much like Genie, we apply the necessary method to the Response
object via textfsm_parse_output
:
import os
from dotenv import load_dotenv
from rich import print
from scrapli import Scrapli
load_dotenv()
# Create device dict()
device = {
"host": "172.29.151.7",
"auth_username": os.getenv("LAB_USERNAME"),
"auth_password": os.getenv("LAB_PASSWORD"),
"auth_strict_key": False,
"platform": "arista_eos",
}
# Scrapli context manager - Instantiate, open and close connection
with Scrapli(**device) as conn:
# Send command to device
response = conn.send_command("show ip interface brief")
# TextFSM parse response
textfsm_parsed_response = response.textfsm_parse_output()