Parse, Audit, Query, Build, and Modify Cisco IOS-style and JunOS-style network configuration files
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive utility functions for DNS operations, text processing, validation, logging control, and Cisco-specific utilities like password decryption and command execution. These tools support advanced network automation workflows and configuration management tasks.
Comprehensive DNS query functionality with support for multiple record types and configurable DNS servers.
def dns_query(query_name, query_type='A', server='8.8.8.8', timeout=0.5):
"""
Perform DNS query for specified record type.
Parameters:
- query_name (str): Domain name to query
- query_type (str): DNS record type ('A', 'AAAA', 'MX', 'NS', 'TXT', etc.)
- server (str): DNS server IP address
- timeout (float): Query timeout in seconds
Returns:
DNSResponse: DNS query response object
"""
def dns_lookup(input_name, timeout=0.5, server='8.8.8.8'):
"""
DNS A record lookup for IPv4 addresses.
Parameters:
- input_name (str): Domain name to resolve
- timeout (float): Query timeout in seconds
- server (str): DNS server IP address
Returns:
list[str]: List of IPv4 addresses
"""
def dns6_lookup(input_name, timeout=0.5, server='8.8.8.8'):
"""
DNS AAAA record lookup for IPv6 addresses.
Parameters:
- input_name (str): Domain name to resolve
- timeout (float): Query timeout in seconds
- server (str): DNS server IP address
Returns:
list[str]: List of IPv6 addresses
"""
def reverse_dns_lookup(input_addr, timeout=0.5, server='8.8.8.8'):
"""
Reverse DNS lookup for hostname resolution.
Parameters:
- input_addr (str): IP address to resolve
- timeout (float): Query timeout in seconds
- server (str): DNS server IP address
Returns:
list[str]: List of hostnames
"""Execute system commands with timeout control and result capture.
def run_this_posix_command(command, timeout=60.0):
"""
Execute POSIX commands with timeout and error handling.
Parameters:
- command (str): Command string to execute
- timeout (float): Command timeout in seconds
Returns:
dict: Command execution results with stdout, stderr, and return code
"""Configure and control logging for ciscoconfparse operations.
def ccp_logger_control(action='disable', sink_path=None, level='INFO'):
"""
Control ciscoconfparse logging configuration.
Parameters:
- action (str): Logging action ('enable', 'disable', 'reset')
- sink_path (str): Log file path (None for console)
- level (str): Log level ('DEBUG', 'INFO', 'WARNING', 'ERROR')
"""
def configure_loguru(sink=None, level='INFO', format=None):
"""
Configure loguru logging system.
Parameters:
- sink (str): Log destination (file path or console)
- level (str): Minimum log level
- format (str): Log message format string
"""
def log_function_call():
"""
Decorator to log function calls for debugging purposes.
Use as @log_function_call() before function definitions.
"""Text manipulation and formatting utilities for configuration processing.
def as_text_list(config, syntax='ios'):
"""
Convert configuration objects to text list format.
Parameters:
- config: Configuration object, text, or list
- syntax (str): Configuration syntax type
Returns:
list[str]: Configuration as list of text lines
"""
def fix_repeated_words(text):
"""
Fix repeated words in configuration text.
Parameters:
- text (str): Input text with potential repeated words
Returns:
str: Text with repeated words removed
"""Enhanced regular expression matching with additional functionality.
class __ccp_re__:
"""Enhanced regular expression utilities for configuration parsing."""
@staticmethod
def search(pattern, string, flags=0):
"""
Enhanced regex search with additional error handling.
Parameters:
- pattern (str): Regular expression pattern
- string (str): String to search
- flags (int): Regex flags
Returns:
Match: Regex match object or None
"""
@staticmethod
def match(pattern, string, flags=0):
"""
Enhanced regex match with additional error handling.
Parameters:
- pattern (str): Regular expression pattern
- string (str): String to match
- flags (int): Regex flags
Returns:
Match: Regex match object or None
"""
@staticmethod
def sub(pattern, repl, string, count=0, flags=0):
"""
Enhanced regex substitution with additional functionality.
Parameters:
- pattern (str): Regular expression pattern
- repl (str): Replacement string
- string (str): Input string
- count (int): Maximum substitutions (0 for all)
- flags (int): Regex flags
Returns:
str: String with substitutions applied
"""Core utilities for configuration parsing and manipulation.
def get_version_number():
"""
Get ciscoconfparse package version.
Returns:
str: Package version string
"""
def initialize_ciscoconfparse():
"""
Initialize ciscoconfparse package with default settings.
Performs package-level initialization and setup.
"""
def parse_line_braces(line):
"""
Parse configuration line with brace syntax support.
Parameters:
- line (str): Configuration line to parse
Returns:
str: Parsed configuration line
"""
def build_space_tolerant_regex(linespec):
"""
Build flexible regex pattern that handles variable whitespace.
Parameters:
- linespec (str): Base pattern specification
Returns:
Pattern: Compiled regex pattern with space tolerance
"""Runtime type checking and validation for function parameters.
def enforce_valid_types(func, args, kwargs):
"""
Enforce valid parameter types for function calls.
Parameters:
- func (callable): Function to validate
- args (tuple): Function positional arguments
- kwargs (dict): Function keyword arguments
Raises:
TypeError: If parameter types don't match expectations
"""Function decorators for enhanced functionality and debugging.
def junos_unsupported():
"""
Decorator to mark functions as unsupported for Junos configurations.
Raises appropriate exceptions when used with Junos syntax.
"""Protocol definitions and port mappings for Cisco ASA configurations.
# Protocol constants from ciscoconfparse.protocol_values
ASA_IP_PROTOCOLS = {
# Dictionary mapping protocol names to numbers
'icmp': 1,
'tcp': 6,
'udp': 17,
# ... additional protocols
}
ASA_TCP_PORTS = {
# Dictionary mapping TCP service names to port numbers
'ftp': 21,
'ssh': 22,
'telnet': 23,
'smtp': 25,
'http': 80,
'https': 443,
# ... additional TCP ports
}
ASA_UDP_PORTS = {
# Dictionary mapping UDP service names to port numbers
'dns': 53,
'dhcp': 67,
'tftp': 69,
'snmp': 161,
# ... additional UDP ports
}All exceptions inherit from BaseError for consistent error handling.
class BaseError(Exception):
"""Base exception class for ciscoconfparse."""
class PythonOptimizeException(BaseError):
"""Python optimization related errors."""
class RequirementFailure(BaseError):
"""Requirement validation failures."""
class ListItemMissingAttribute(BaseError):
"""Missing attribute in list item operations."""
class ListItemTypeError(BaseError):
"""Type errors in list item operations."""
class DNSLookupError(BaseError):
"""DNS lookup operation failures."""
class DNSTimeoutError(BaseError):
"""DNS query timeout errors."""
class DuplicateMember(BaseError):
"""Duplicate member errors in collections."""
class DynamicAddressException(BaseError):
"""Dynamic address handling errors."""
class InvalidCiscoInterface(BaseError):
"""Invalid Cisco interface specifications."""
class InvalidCiscoEthernetTrunkAction(BaseError):
"""Invalid Ethernet trunk action configurations."""
class InvalidCiscoEthernetVlan(BaseError):
"""Invalid VLAN specifications."""
class InvalidMember(BaseError):
"""Invalid member in collection operations."""
class InvalidParameters(BaseError):
"""Invalid function parameter errors."""
class InvalidCiscoRange(BaseError):
"""Invalid Cisco range format specifications."""
class InvalidShellVariableMapping(BaseError):
"""Invalid shell variable mapping errors."""
class InvalidTypecast(BaseError):
"""Invalid type casting operations."""
class NoRegexMatch(BaseError):
"""No regex match found errors."""
class MismatchedType(BaseError):
"""Type mismatch errors."""
class UnexpectedType(BaseError):
"""Unexpected type errors."""
class UntypedError(BaseError):
"""Untyped error conditions."""from ciscoconfparse import dns_lookup, dns6_lookup, reverse_dns_lookup, dns_query
# Basic DNS lookups
ipv4_addresses = dns_lookup('www.cisco.com')
print(f"IPv4 addresses: {ipv4_addresses}")
ipv6_addresses = dns6_lookup('www.cisco.com')
print(f"IPv6 addresses: {ipv6_addresses}")
# Reverse DNS lookup
hostnames = reverse_dns_lookup('8.8.8.8')
print(f"Hostnames: {hostnames}")
# Advanced DNS query
mx_response = dns_query('cisco.com', query_type='MX')
print(f"MX record: {mx_response.response}")
print(f"Preference: {mx_response.preference}")from ciscoconfparse import run_this_posix_command
# Execute system command with timeout
result = run_this_posix_command('ping -c 3 8.8.8.8', timeout=10.0)
print(f"Return code: {result['returncode']}")
print(f"Output: {result['stdout']}")
if result['stderr']:
print(f"Errors: {result['stderr']}")from ciscoconfparse import ccp_logger_control, configure_loguru
# Enable logging to file
ccp_logger_control(action='enable', sink_path='ciscoconfparse.log', level='DEBUG')
# Configure loguru logging
configure_loguru(sink='debug.log', level='INFO', format='{time} {level} {message}')
# Disable logging
ccp_logger_control(action='disable')from ciscoconfparse.protocol_values import ASA_TCP_PORTS, ASA_UDP_PORTS, ASA_IP_PROTOCOLS
# Look up well-known ports
http_port = ASA_TCP_PORTS['http'] # 80
https_port = ASA_TCP_PORTS['https'] # 443
dns_port = ASA_UDP_PORTS['dns'] # 53
# Look up protocol numbers
tcp_proto = ASA_IP_PROTOCOLS['tcp'] # 6
udp_proto = ASA_IP_PROTOCOLS['udp'] # 17
print(f"HTTP runs on TCP port {http_port}")
print(f"DNS runs on UDP port {dns_port}")from ciscoconfparse import as_text_list, fix_repeated_words
# Convert configuration to text list
config_lines = as_text_list(parse, syntax='ios')
print(f"Configuration has {len(config_lines)} lines")
# Fix repeated words in text
corrected_text = fix_repeated_words("interface interface GigabitEthernet0/1")
print(f"Corrected: {corrected_text}") # "interface GigabitEthernet0/1"from ciscoconfparse import get_version_number
version = get_version_number()
print(f"CiscoConfParse version: {version}")from ciscoconfparse.ccp_util import __ccp_re__
# Enhanced regex operations
pattern = r'interface.*GigabitEthernet'
text = "interface GigabitEthernet0/1"
match = __ccp_re__.search(pattern, text)
if match:
print(f"Found match: {match.group()}")
# Enhanced substitution
new_text = __ccp_re__.sub(r'GigabitEthernet', 'Gi', text)
print(f"Abbreviated: {new_text}") # "interface Gi0/1"from ciscoconfparse import CiscoConfParse, InvalidCiscoInterface, DNSLookupError
try:
# This might raise InvalidCiscoInterface
parse = CiscoConfParse('config.txt', syntax='ios')
interface_obj = parse.find_objects(r'^interface InvalidName')[0]
except InvalidCiscoInterface as e:
print(f"Interface error: {e}")
except DNSLookupError as e:
print(f"DNS error: {e}")
except BaseError as e:
print(f"CiscoConfParse error: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-ciscoconfparse