CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-textfsm

Python module for parsing semi-structured text into python tables.

Overview
Eval results
Files

cli-tables.mddocs/

CLI Table Management

The CLI table functionality provides automated template selection and parsing for network device command outputs. It uses index files to map TextFSM templates to specific device types and commands, enabling automated parsing of CLI data without manual template selection.

Core Imports

from textfsm import clitable
from textfsm.clitable import CliTable, IndexTable
from textfsm.clitable import CliTableError, IndexTableError

Capabilities

CliTable Parser

Automated CLI data parser that uses index files to select appropriate templates based on device attributes and command patterns.

class CliTable(texttable.TextTable):
    def __init__(self, index_file=None, template_dir=None):
        """
        Initialize CLI table parser.
        
        Args:
            index_file (str): Path to index file mapping templates to devices/commands
            template_dir (str): Directory containing TextFSM template files
        """
    
    def ParseCmd(self, cmd_input, attributes=None, templates=None):
        """
        Parse command output using automatic template selection.
        
        Args:
            cmd_input (str): Raw command output text to parse
            attributes (dict): Device attributes for template matching
                              (e.g., {'Platform': 'cisco_ios', 'Command': 'show version'})
            templates (list): Specific template files to use (optional)
        
        Returns:
            bool: True if parsing successful, False otherwise
        """
    
    def AddKeys(self, keys):
        """
        Add key fields to the table structure.
        
        Args:
            keys (list): List of key field names
        """
    
    def ReadIndex(self, index_file=None):
        """
        Read template index file.
        
        Args:
            index_file (str): Path to index file (optional)
        """
    
    def sort(self, cmp=None, key=None, reverse=False):
        """
        Sort table rows.
        
        Args:
            cmp: Comparison function (deprecated)
            key: Key function for sorting
            reverse (bool): Sort in reverse order
        """
    
    def KeyValue(self, row=None):
        """
        Get key values for a row.
        
        Args:
            row: Row to get keys from (default: current row)
            
        Returns:
            list: List of key field values
        """
    
    def LabelValueTable(self, keys=None):
        """
        Format table as label-value pairs.
        
        Args:
            keys (list): Keys to include (optional)
            
        Returns:
            str: Formatted label-value table
        """
    
    @property
    def index_table(self):
        """IndexTable object containing template mappings."""
    
    @property
    def template_dir(self):
        """Directory path containing template files."""
    
    @property
    def raw(self):
        """Raw unparsed command output."""
    
    @property
    def superkey(self):
        """Combined key for table identification."""

Index Table Management

Manages index files that define mappings between device attributes, commands, and TextFSM template files.

class IndexTable(object):
    def __init__(self, preread=None, precompile=None, file_path=None):
        """
        Initialize index table from file or data.
        
        Args:
            preread: Pre-read data for index
            precompile: Pre-compile regex patterns
            file_path (str): Path to index file
        """
    
    def GetRowMatch(self, attributes):
        """
        Find index rows matching specified criteria.
        
        Args:
            attributes (dict): Attribute key-value pairs to match
                             (e.g., {'Platform': 'cisco_ios', 'Command': 'show version'})
        
        Returns:
            int: Index of first matching row, or -1 if not found
        """
    
    def __del__(self):
        """Destructor."""
    
    def __len__(self):
        """
        Get number of rows in index.
        
        Returns:
            int: Number of rows
        """
    
    def __copy__(self):
        """Create shallow copy."""
    
    def __deepcopy__(self, memodict=None):
        """Create deep copy."""
    
    @property
    def header(self):
        """List of column headers."""
    
    @property
    def index(self):
        """List of index rows."""
    
    @property
    def compiled(self):
        """Compiled regex patterns for matching."""

Usage Examples

Basic CLI Table Usage

from textfsm import clitable

# Initialize with index file and template directory
cli_table = clitable.CliTable('index.csv', 'templates/')

# Parse command output with device attributes
attributes = {
    'Platform': 'cisco_ios',
    'Command': 'show version'
}

cmd_output = """
Cisco IOS Software, C2900 Software (C2900-UNIVERSALK9-M), Version 15.1(4)M5
Router uptime is 5 days, 14 hours, 23 minutes
"""

success = cli_table.ParseCmd(cmd_output, attributes)
if success:
    print(cli_table.FormattedTable())

Working with Index Tables

from textfsm import clitable

# Create index table
index = clitable.IndexTable()

# Add mappings
index.AddRow(['cisco_ios', 'show version', 'cisco_ios_show_version.textfsm'])
index.AddRow(['cisco_ios', 'show interfaces', 'cisco_ios_show_interfaces.textfsm'])

# Find matching templates
matches = index.GetRowMatch(Platform='cisco_ios', Command='show version')
print(matches)  # Returns matching rows

Index File Format

Index files are CSV format with columns defining device attributes and template mappings:

Platform,Command,Template
cisco_ios,show version,cisco_ios_show_version.textfsm
cisco_ios,show interfaces,cisco_ios_show_interfaces.textfsm
cisco_nxos,show version,cisco_nxos_show_version.textfsm
juniper_junos,show version,juniper_junos_show_version.textfsm

Custom Attribute Matching

# Use custom attributes for template selection
custom_attributes = {
    'Platform': 'cisco_ios',
    'Command': 'show ip route',
    'Version': '15.1',
    'Model': 'C2900'
}

cli_table = clitable.CliTable('advanced_index.csv', 'templates/')
success = cli_table.ParseCmd(route_output, custom_attributes)

Error Handling

from textfsm import clitable

try:
    cli_table = clitable.CliTable('index.csv', 'templates/')
    success = cli_table.ParseCmd(cmd_output, attributes)
    
    if not success:
        print("No matching template found or parsing failed")
    else:
        # Process results
        for row in cli_table:
            print(row)
            
except clitable.CliTableError as e:
    print(f"CLI table error: {e}")
except clitable.IndexTableError as e:
    print(f"Index table error: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-textfsm

docs

cli-tables.md

core-parser.md

index.md

terminal-utils.md

text-tables.md

tile.json