CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-ciscoconfparse

Parse, Audit, Query, Build, and Modify Cisco IOS-style and JunOS-style network configuration files

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

core-parsing.mddocs/

Core Configuration Parsing

Comprehensive functionality for parsing, querying, and modifying network configurations. The CiscoConfParse class provides the primary interface for working with configuration files, supporting regex-based searches, parent-child relationship queries, and in-place modifications.

Capabilities

Configuration Parser Initialization

Initialize the parser with configuration data and syntax-specific options.

class CiscoConfParse:
    def __init__(
        self, 
        config, 
        syntax='ios', 
        comment_delimiter='!', 
        debug=False, 
        factory=False, 
        ignore_blank_lines=True, 
        encoding='utf-8'
    ):
        """
        Initialize configuration parser.
        
        Parameters:
        - config (str|list): Configuration file path, text, or list of lines
        - syntax (str): Configuration syntax ('ios', 'nxos', 'asa', 'iosxr', 'junos')
        - comment_delimiter (str): Character marking comment lines
        - debug (bool): Enable debug logging
        - factory (bool): Use factory parsing for enhanced object types
        - ignore_blank_lines (bool): Skip blank lines during parsing
        - encoding (str): File encoding for text files
        """

Configuration Object Search

Find configuration objects matching specified patterns with support for exact matching and whitespace handling.

def find_objects(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Find configuration objects matching linespec pattern.
    
    Parameters:
    - linespec (str): Regular expression pattern to match
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Configuration line objects matching the pattern
    """

def find_lines(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Find configuration line text matching linespec pattern.
    
    Parameters:
    - linespec (str): Regular expression pattern to match
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list[str]: Configuration line text matching the pattern
    """

def find_blocks(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Find configuration blocks starting with linespec pattern.
    
    Parameters:
    - linespec (str): Regular expression pattern to match parent lines
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list[list]: Lists of configuration lines, each starting with matching parent
    """

def find_object_branches(self, branchspec=(), regex_flags=0, allow_none=True, regex_groups=False, debug=0):
    """
    Find nested object hierarchies matching complex branch specifications.
    
    Parameters:
    - branchspec (tuple): Nested regex patterns for hierarchical matching
    - regex_flags (int): Regex compilation flags
    - allow_none (bool): Allow None matches in branches
    - regex_groups (bool): Return regex groups in results
    - debug (int): Debug level
    
    Returns:
    list: Nested configuration object hierarchies
    """

def find_objects_dna(self, dnaspec, exactmatch=False):
    """
    Find objects using DNA matching patterns.
    
    Parameters:
    - dnaspec (str): DNA specification pattern
    - exactmatch (bool): Require exact matching
    
    Returns:
    list: Configuration objects matching DNA pattern
    """

Hierarchical Relationship Queries

Search based on parent-child relationships in configuration hierarchy.

def find_children(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Find direct child lines of configuration objects matching linespec.
    
    Parameters:
    - linespec (str): Regular expression pattern for parent lines
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Child configuration objects of matching parents
    """

def find_all_children(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Find all descendant lines of configuration objects matching linespec.
    
    Parameters:
    - linespec (str): Regular expression pattern for parent lines
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: All descendant configuration objects of matching parents
    """

def find_objects_w_child(self, parentspec, childspec, ignore_ws=False):
    """
    Find parent objects that have children matching childspec.
    
    Parameters:
    - parentspec (str): Regular expression pattern for parent lines
    - childspec (str): Regular expression pattern for required child lines
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Parent configuration objects with matching children
    """

def find_parents_w_child(self, parentspec, childspec, ignore_ws=False):
    """
    Find parent line text that has children matching childspec.
    
    Parameters:
    - parentspec (str): Regular expression pattern for parent lines
    - childspec (str): Regular expression pattern for required child lines
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list[str]: Parent configuration line text with matching children
    """

def find_objects_wo_child(self, parentspec, childspec, ignore_ws=False):
    """
    Find parent objects that do NOT have children matching childspec.
    
    Parameters:
    - parentspec (str): Regular expression pattern for parent lines
    - childspec (str): Regular expression pattern for excluded child lines
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Parent configuration objects without matching children
    """

def find_objects_w_all_children(self, parentspec, childspec, ignore_ws=False, recurse=False):
    """
    Find parent objects that have ALL specified children.
    
    Parameters:
    - parentspec (str): Regular expression pattern for parent lines
    - childspec (list): List of required child patterns
    - ignore_ws (bool): Ignore whitespace differences
    - recurse (bool): Search recursively in descendants
    
    Returns:
    list: Parent objects with all required children
    """

def find_objects_w_missing_children(self, parentspec, childspec, ignore_ws=False, recurse=False):
    """
    Find parent objects missing some of the specified children.
    
    Parameters:
    - parentspec (str): Regular expression pattern for parent lines
    - childspec (list): List of expected child patterns
    - ignore_ws (bool): Ignore whitespace differences
    - recurse (bool): Search recursively in descendants
    
    Returns:
    list: Parent objects missing required children
    """

def find_lineage(self, linespec, exactmatch=False):
    """
    Find complete ancestry lineage for configuration objects.
    
    Parameters:
    - linespec (str): Regular expression pattern for target lines
    - exactmatch (bool): Require exact string match
    
    Returns:
    list: Complete ancestry chains for matching objects
    """

Interface-Specific Search

Specialized search functionality for network interface configurations.

def find_interface_objects(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Find interface configuration objects matching linespec pattern.
    
    Parameters:
    - linespec (str): Regular expression pattern for interface lines
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Interface configuration objects matching the pattern
    """

Advanced Search Methods

Regex-based search with type conversion and pattern matching.

def re_search_children(self, regexspec, recurse=False):
    """
    Search children using regex patterns.
    
    Parameters:
    - regexspec (str): Regular expression pattern
    - recurse (bool): Search recursively in all descendants
    
    Returns:
    list: Children matching regex pattern
    """

def re_match_iter_typed(self, regexspec, group=1, result_type=str, default="", untyped_default=False, groupdict={}, recurse=False, debug=0):
    """
    Advanced regex matching with automatic type conversion.
    
    Parameters:
    - regexspec (str): Regular expression pattern with groups
    - group (int): Regex group number to extract
    - result_type (type): Type to convert results to (str, int, float, etc.)
    - default: Default value for failed matches
    - untyped_default (bool): Use untyped default values
    - groupdict (dict): Named group mappings
    - recurse (bool): Search recursively
    - debug (int): Debug level
    
    Returns:
    generator: Type-converted regex match results
    """

Configuration Modification

Insert, delete, and replace configuration lines with automatic hierarchy management.

def insert_before(self, linespec, insertstr, exactmatch=False, ignore_ws=False):
    """
    Insert new configuration lines before existing lines matching linespec.
    
    Parameters:
    - linespec (str): Regular expression pattern for target lines
    - insertstr (str|list): Configuration text to insert
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Inserted configuration line objects
    """

def insert_after(self, linespec, insertstr, exactmatch=False, ignore_ws=False):
    """
    Insert new configuration lines after existing lines matching linespec.
    
    Parameters:
    - linespec (str): Regular expression pattern for target lines
    - insertstr (str|list): Configuration text to insert
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Inserted configuration line objects
    """

def delete_lines(self, linespec, exactmatch=False, ignore_ws=False):
    """
    Delete configuration lines matching linespec pattern.
    
    Parameters:
    - linespec (str): Regular expression pattern for lines to delete
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: Deleted configuration line objects
    """

def replace_lines(self, linespec, replacestr, exactmatch=False, ignore_ws=False):
    """
    Replace configuration lines matching linespec with new text.
    
    Parameters:
    - linespec (str): Regular expression pattern for lines to replace
    - replacestr (str): Replacement configuration text
    - exactmatch (bool): Require exact string match instead of regex
    - ignore_ws (bool): Ignore whitespace differences
    
    Returns:
    list: New configuration line objects after replacement
    """

def sync_diff(self, cfgspec=None, ignore_order=True, remove_lines=True, debug=0):
    """
    Synchronize configuration with target specification.
    
    Parameters:
    - cfgspec (list): Target configuration specification
    - ignore_order (bool): Ignore line ordering in comparison
    - remove_lines (bool): Remove lines not in target spec
    - debug (int): Debug level
    
    Returns:
    list: Configuration changes needed for synchronization
    """

def replace_children(self, parentspec, childspec, replacestr, ignore_ws=False, exactmatch=False, excludespec=None, atomic=False):
    """
    Replace child lines matching patterns under parent objects.
    
    Parameters:
    - parentspec (str): Parent line pattern
    - childspec (str): Child line pattern to replace
    - replacestr (str): Replacement text
    - ignore_ws (bool): Ignore whitespace
    - exactmatch (bool): Exact string matching
    - excludespec (str): Pattern to exclude from replacement
    - atomic (bool): Atomic operation
    
    Returns:
    list: Replaced configuration objects
    """

def replace_all_children(self, parentspec, replacestr, ignore_ws=False, exactmatch=False, atomic=False):
    """
    Replace all children under parent objects.
    
    Parameters:
    - parentspec (str): Parent line pattern
    - replacestr (str): Replacement text for all children
    - ignore_ws (bool): Ignore whitespace
    - exactmatch (bool): Exact string matching
    - atomic (bool): Atomic operation
    
    Returns:
    list: Replaced configuration objects
    """

Configuration Management

Commit changes and save configurations to files.

def commit(self):
    """
    Commit all pending configuration changes to the internal text list.
    Must be called after modification operations to apply changes.
    
    Returns:
    list[str]: Updated configuration as list of text lines
    """

def save_as(self, filepath):
    """
    Save current configuration to a file.
    
    Parameters:
    - filepath (str): Target file path for saving configuration
    
    Returns:
    str: Path of saved configuration file
    """

Configuration Comparison

Difference Detection

Compare configurations and generate difference reports.

class Diff:
    def __init__(self, old_config, new_config, syntax='ios'):
        """
        Initialize configuration difference analyzer.
        
        Parameters:
        - old_config (str|list): Original configuration
        - new_config (str|list): Updated configuration  
        - syntax (str): Configuration syntax type
        """
    
    def get_diff(self):
        """
        Generate configuration differences.
        
        Returns:
        dict: Difference analysis results
        """

class HDiff:
    """Hierarchical configuration difference analysis."""

class DiffObject:
    """Represents individual configuration differences."""

Password Handling

Cisco Password Decryption

Decrypt Cisco Type 7 and other password formats.

class CiscoPassword:
    def __init__(self, ep=None):
        """
        Initialize password handler.
        
        Parameters:
        - ep (str): Encrypted password string
        """
    
    def decrypt(self, ep):
        """
        Decrypt Cisco password.
        
        Parameters:
        - ep (str): Encrypted password string
        
        Returns:
        str: Decrypted password text
        """

Configuration Container

ConfigList Container

Mutable sequence container for configuration line objects.

class ConfigList:
    def __init__(
        self, 
        data, 
        comment_delimiter='!', 
        debug=False, 
        factory=False, 
        ignore_blank_lines=True, 
        syntax='ios', 
        ccp_ref=None
    ):
        """
        Initialize configuration list container.
        
        Parameters:
        - data (list): Configuration data
        - comment_delimiter (str): Comment line delimiter
        - debug (bool): Enable debug mode
        - factory (bool): Use factory parsing
        - ignore_blank_lines (bool): Skip blank lines
        - syntax (str): Configuration syntax
        - ccp_ref: CiscoConfParse reference
        """
    
    def append(self, val):
        """Add configuration line to end of list."""
    
    def insert(self, index, val):
        """Insert configuration line at specified index."""
    
    def __getitem__(self, key):
        """Get configuration line by index or slice."""
    
    def __setitem__(self, key, val):
        """Set configuration line by index or slice."""
    
    def __delitem__(self, key):
        """Delete configuration line by index or slice."""

Usage Examples

Basic Configuration Parsing

from ciscoconfparse import CiscoConfParse

# Parse configuration file
parse = CiscoConfParse('switch_config.txt', syntax='ios')

# Find all VLAN configurations
vlans = parse.find_objects(r'^vlan \d+')
for vlan in vlans:
    print(f"VLAN: {vlan.text}")
    for child in vlan.children:
        print(f"  {child.text}")

Hierarchical Queries

# Find interfaces configured as trunks
trunk_interfaces = parse.find_objects_w_child(
    parentspec=r'^interface', 
    childspec=r'switchport mode trunk'
)

# Find BGP neighbors with specific attributes
bgp_neighbors = parse.find_objects_w_child(
    parentspec=r'router bgp',
    childspec=r'neighbor.*remote-as'
)

Configuration Modification

# Add description to all interfaces
interfaces = parse.find_objects(r'^interface')
for intf in interfaces:
    if not any('description' in child.text for child in intf.children):
        parse.insert_after(intf.text, ' description MANAGED_BY_AUTOMATION')

# Commit and save changes
parse.commit()
parse.save_as('updated_config.txt')

Install with Tessl CLI

npx tessl i tessl/pypi-ciscoconfparse

docs

core-parsing.md

index.md

interface-parsing.md

network-objects.md

utilities.md

tile.json