### Simple CiscoConfParse Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md A basic example demonstrating how to parse a Cisco configuration file and find lines matching a specific string. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Find lines that start with 'hostname' hostname_lines = parse.find_lines("hostname") # Find lines that start with 'interface' interface_lines = parse.find_lines("interface") ``` -------------------------------- ### Install ciscoconfparse2 using pip Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Install the library using pip. Ensure you have a requirements.txt file for managing dependencies. ```bash pip install ciscoconfparse2 ``` ```bash pip install -r requirements.txt ``` -------------------------------- ### Build ciscoconfparse Documentation Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/README.md Navigate to the sphinx-doc directory, install the package, and build the HTML documentation. ```bash cd sphinx-doc/ ``` ```bash pip install ciscoconfparse ``` ```bash make html ``` -------------------------------- ### Rollback Script Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md A conceptual example of a rollback script, likely intended to revert configuration changes. ```python # This is a conceptual example and requires specific implementation details # based on the diff output and target device. from ciscoconfparse import CiscoConfParse def rollback_config(original_conf_path, current_conf_path): conf_orig = CiscoConfParse(original_conf_path) conf_curr = CiscoConfParse(current_conf_path) # Generate commands to revert changes # This would involve analyzing the diff between conf_orig and conf_curr # and generating the appropriate 'no' commands or specific configurations. rollback_commands = conf_curr.diff_from(conf_orig) # Note: diff_from shows changes FROM conf1 TO conf2 # For rollback, we want changes FROM conf2 TO conf1 # So, we'd likely need to reverse the logic or commands. print("Rollback commands to apply:") for cmd in rollback_commands: print(cmd) # Example usage (requires actual configuration files) # rollback_config("bucksnort_before.conf", "bucksnort_after.conf") ``` -------------------------------- ### Install ciscoconfparse2 Source: https://github.com/mpenning/ciscoconfparse2/blob/main/README.md Use pip to install the ciscoconfparse2 package for Python 3.x. ```bash python -m pip install ciscoconfparse2 ``` -------------------------------- ### CLI Example: Find Branches as Lists Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Command-line usage to extract configuration branches and display them as lists. ```bash ccp myconfig.conf --find-branches-as-list "^interface" ``` -------------------------------- ### Build Configuration Diffs Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Example script for building configuration differences between two Cisco configuration files. ```python from ciscoconfparse import CiscoConfParse # Load configurations conf1 = CiscoConfParse("bucksnort_before.conf") conf2 = CiscoConfParse("bucksnort_after.conf") # Get differences diffs = conf1.diff_from(conf2) # Print differences for diff in diffs: print(diff) ``` -------------------------------- ### CLI Example: Find Parent Lines Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Command-line usage to find parent configuration lines matching a pattern. ```bash ccp myconfig.conf --find "^interface" ``` -------------------------------- ### CiscoRange Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Demonstrates the usage of CiscoRange for parsing interface ranges. ```python from ciscoconfparse import CiscoConfParse from ciscoconfparse.ccp_range import CiscoRange parse = CiscoConfParse("myconfig.conf") # Get all interface ranges interface_ranges = parse.find_objects_w_child(CiscoRange, "^interface") # Check if a specific interface is within a range for r in interface_ranges: if "GigabitEthernet1/0/1" in r: print(f"GigabitEthernet1/0/1 is in range {r.name}") ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/development.md Install the latest versions of ciscoconfparse2, pytest, and pytest-cov to run test coverage reports. Assumes the latest code is available on PyPI. ```shell # Install the latest ciscoconfparse2 # (assuming the latest code is on pypi) $ pip install -U ciscoconfparse2 $ pip install -U pytest-cov ``` -------------------------------- ### Display Baseline Configurations Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_build_diffs.md These are example baseline configurations used for diffing. 'bucksnort_before.conf' represents the initial state, and 'bucksnort_after.conf' shows the state after changes. ```none ! Filename: /tftpboot/bucksnort_before.conf ! hostname bucksnort ! interface Ethernet0/0 ip address 1.1.2.1 255.255.255.0 no cdp enable ! interface Serial1/0 encapsulation ppp ip address 1.1.1.1 255.255.255.252 ! interface Serial1/1 encapsulation ppp ip address 1.1.1.5 255.255.255.252 ! ``` ```none ! Filename: /tftpboot/bucksnort_after.conf ! hostname bucksnort ! interface Ethernet0/0 ip address 1.1.2.1 255.255.255.0 no cdp enable ! interface Serial1/0 encapsulation ppp ip address 1.1.1.1 255.255.255.252 mpls ip ! interface Serial1/1 encapsulation ppp ip address 1.1.1.5 255.255.255.252 ! ``` -------------------------------- ### Complex CiscoConfParse Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md An example showcasing more advanced parsing techniques, including finding lines with specific regular expressions and iterating through children. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Find lines that start with 'interface' and have an IP address interface_ip_lines = parse.find_lines(r"^interface.*", include_children=True) # Find all lines that contain an IP address all_ip_lines = parse.find_lines_containing_ip() # Find all lines that contain an IP address within a specific subnet subnet_ip_lines = parse.find_lines_containing_ip("192.168.1.0/24") ``` -------------------------------- ### ciscoconfparse2 Deployment Output Source: https://github.com/mpenning/ciscoconfparse2/blob/main/dev_tools/deploy_docs.go/README.md Example output from the './deploy_docs' command, showing the progress of uploading documentation via SSH. ```shell $ ./deploy_docs 2023-06-23T09:13:24.844-0500 INFO deploy_docs/deploy_docs.go:16 Starting ciscoconfparse2 new documentation upload 2023-06-23T09:13:24.844-0500 INFO deploy_docs/deploy_docs.go:18 Initialize ssh key-auth 2023-06-23T09:13:24.844-0500 INFO deploy_docs/deploy_docs.go:25 ssh into remote webhost 2023-06-23T09:13:25.477-0500 INFO deploy_docs/deploy_docs.go:31 Remove old documentation files 2023-06-23T09:13:25.937-0500 INFO deploy_docs/deploy_docs.go:37 Start copying doc tarball to remote ssh server 2023-06-23T09:13:28.659-0500 INFO deploy_docs/deploy_docs.go:42 Finished copying tarball to remote ssh server 2023-06-23T09:13:28.659-0500 INFO deploy_docs/deploy_docs.go:44 extract CiscoConfParse documentation tarball $ ``` -------------------------------- ### CLI Example: Find Child Lines Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Command-line usage to find child configuration lines within parent blocks matching a pattern. ```bash ccp myconfig.conf --find-children "^interface" "^ip address" ``` -------------------------------- ### CiscoRange() Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Basic usage of the CiscoRange class to represent and manage ranges of interfaces. ```python from ciscoconfparse.ccp_range import CiscoRange # Example range: GigabitEthernet1/0/1 - 1/0/5 range_obj = CiscoRange("GigabitEthernet1/0/1-5") print(f"Range name: {range_obj.name}") print(f"Interfaces in range: {range_obj.ios}") ``` -------------------------------- ### CLI Example: Find Branches as Original Configuration Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Command-line usage to extract configuration branches and display them in their original configuration format. ```bash ccp myconfig.conf --find-branches "^interface" ``` -------------------------------- ### re_match_typed() Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Demonstrates how to use `re_match_typed()` to extract a specific value from a configuration line based on a regular expression. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Get the IP address from an interface line interface_line = parse.find_lines("interface GigabitEthernet0/1")[0] # Use re_match_typed to get the IP address ip_address = interface_line.re_match_typed(r"ip address (\S+)", result_type=str) print(f"IP Address: {ip_address}") ``` -------------------------------- ### re_match_iter_typed() Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Shows how to use `re_match_iter_typed()` to iterate over all child lines of a configuration object and extract specific values. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Get an interface object interface_obj = parse.find_objects("interface GigabitEthernet0/1")[0] # Iterate over children and get all configured IP addresses ip_addresses = interface_obj.re_match_iter_typed(r"ip address (\S+)", result_type=str) for ip in ip_addresses: print(f"Found IP: {ip}") ``` -------------------------------- ### IOS Parent-Child Relationship Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Retrieves text from an `IOSCfgLine` object, demonstrating the parent-child relationship in Cisco IOS configurations. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Find an interface line interface_line = parse.find_lines("interface GigabitEthernet0/1")[0] # Access the text of the line itself print(f"Line text: {interface_line.text}") # Access the parent object (e.g., the configuration block) parent_obj = interface_line.parent # Access children commands under this interface for child in interface_line.children: print(f"Child command: {child.text}") ``` -------------------------------- ### CiscoRange() Contents Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Retrieves the list of individual interface names that constitute a `CiscoRange` object. ```python from ciscoconfparse.ccp_range import CiscoRange range_obj = CiscoRange("GigabitEthernet1/0/1-3,1/0/5") # Get the list of all individual interface names interface_list = range_obj.ios print("Interfaces in the range:") for interface in interface_list: print(interface) ``` -------------------------------- ### CiscoRange() Contains Example Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Demonstrates checking if a specific interface name is contained within a `CiscoRange` object. ```python from ciscoconfparse.ccp_range import CiscoRange range_obj = CiscoRange("GigabitEthernet1/0/1-5") # Check if 'GigabitEthernet1/0/3' is in the range if "GigabitEthernet1/0/3" in range_obj: print("'GigabitEthernet1/0/3' is in the range.") else: print("'GigabitEthernet1/0/3' is NOT in the range.") # Check if 'GigabitEthernet1/0/10' is in the range if "GigabitEthernet1/0/10" in range_obj: print("'GigabitEthernet1/0/10' is in the range.") else: print("'GigabitEthernet1/0/10' is NOT in the range.") ``` -------------------------------- ### re_list_iter_typed() Example for Interfaces Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Demonstrates using `re_list_iter_typed()` to retrieve multiple values, such as IP addresses, from all interface configurations. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Get all interface objects interface_objs = parse.find_objects("^interface") # Iterate through all interfaces and extract IP addresses for interface in interface_objs: ip_addresses = interface.re_match_iter_typed(r"ip address (\S+)", result_type=str) for ip in ip_addresses: print(f"Interface {interface.name} has IP: {ip}") ``` -------------------------------- ### CLI Example: Find IP Addresses within CIDR Range Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Command-line usage to find IP addresses within a specified CIDR range in a configuration file. ```bash ccp myconfig.conf --find-ip-in-cidr "192.168.1.0/24" ``` -------------------------------- ### Find Interface Names Matching Substring Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Example of finding interface names that contain a specific substring using `CiscoConfParse`. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Find interfaces containing 'GigabitEthernet' interfaces = parse.find_objects_w_child(r"^interface.*GigabitEthernet.*", "^ip address") for intf in interfaces: print(f"Found interface: {intf.name}") ``` -------------------------------- ### Find Interface Names Matching a Substring Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_parent_child.md Loads a configuration file and uses find_objects() with a regular expression to locate lines starting with 'interface Serial'. The results are stored as IOSCfgLine objects. ```python from ciscoconfparse2.ciscoconfparse2 import CiscoConfParse parse = CiscoConfParse("/tftpboot/bucksnort.conf") serial_objs = parse.find_objects("^interface Serial") ``` ```python serial_objs [, , ] ``` ```python for obj in serial_objs: print(obj.text) interface Serial1/0 interface Serial1/1 interface Serial1/2 ``` -------------------------------- ### Find Configuration Branches with find_object_branches Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_configuration_branches.md Use `find_object_branches()` to retrieve a parent configuration line along with its children and grandchildren. This is useful for getting entire configuration blocks at once. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> config = """!\n... router bgp 65534\n... neighbor 10.0.0.1\n... remote-as 65534\n... """ >>> parse = CiscoConfParse(config) >>> >>> branches = parse.find_object_branches((r'router bgp', r'neighbor', r'remote-as')) >>> branches [Branch(['router bgp 65534', ' neighbor 10.0.0.1', ' remote-as 65534'])] >>> >>> branches[0][0] >>> >>> branches[0][1] >>> >>> branches[0][2] >>> ``` -------------------------------- ### Instantiate and Inspect IOSCfgLine Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Demonstrates creating a CiscoConfParse object and finding a 'hostname' command, showing its representation as an IOSCfgLine object. ```python >>> from ciscoconfparse2.models_cisco import IOSCfgLine >>> from ciscoconfparse2.ccp_abc import BaseCfgLine >>> from ciscoconfparse2 import CiscoConfParse >>> >>> parse = CiscoConfParse(['hostname Foo'], syntax='ios') >>> cmd = parse.find_objects('hostname')[0] >>> >>> cmd >>> >>> str(cmd) 'hostname Foo' >>> >>> issubclass(IOSCfgLine, BaseCfgLine) True >>> ``` -------------------------------- ### Build and Run ciscoconfparse2 Tool Source: https://github.com/mpenning/ciscoconfparse2/blob/main/dev_tools/deploy_docs.go/README.md Use 'make build' to compile the tool and download dependencies. Run the compiled tool with './deploy_docs'. ```shell make build ``` ```shell ./deploy_docs ``` -------------------------------- ### Get HSRP IP using re_match_iter_typed() on a specific object Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md When needing to extract a value from a specific configuration object (like an interface), first use `find_objects()` to get the object, then use `re_match_iter_typed()` on that object. The `default` parameter provides a fallback value. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse('short.conf') >>> intf_cmd = parse.find_objects(r'^interface\s+Vlan10$')[0] >>> hsrp_ip = intf_cmd.re_match_iter_typed(r'standby\s10\sip\s(\S+)', ... default='') >>> hsrp_ip '192.0.2.1' >>> ``` -------------------------------- ### ccp ipgrep Help and Options Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md Displays the help message for `ccp ipgrep`, outlining all available options, required arguments, and their descriptions. This includes options for specifying subnets, word delimiters, and output modes (lines or unique IPs). ```bash $ ccp ipgrep -h usage: ccp ipgrep [-h] [-s SUBNETS] [-w WORD_DELIMITER] [-l | -u] [ipgrep_file] options: -h, --help show this help message and exit required: ipgrep_file Grep for IPs in these files, defaults to STDIN. -s SUBNETS, --subnets SUBNETS Comma-separated IPv4 and/or IPv6 addresses or prefixes, such as '192.0.2.1,2001:db8::/32'. If the mask is not specified, a host-mask assumed. optional: -w WORD_DELIMITER, --word_delimiter WORD_DELIMITER Word delimiter regular expression, defaults to all whitespace. Join multiple regex delimiters with a pipe character. -l, --line Enable line mode (return lines instead of only returning the IP) -u, --unique Only print unique IPs (remove duplicates) ``` -------------------------------- ### Add ciscoconfparse2 to requirements.txt Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/installation.md Include this line in your requirements.txt file for direct PyPI dependency management. ```text ciscoconfparse2==0.9.18 ``` -------------------------------- ### Accessing Parent and Children of Config Lines Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Illustrates how to use the `.parent` and `.children` attributes of BaseCfgLine objects to navigate the configuration hierarchy. Requires a multi-line configuration string. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> >>> config = """!\n... interface Ethernet1/1\n... ip address 192.0.2.1 255.255.255.0\n... shutdown\n... !""" >>> >>> parse = CiscoConfParse(config.splitlines()) >>> >>> intf_cmd = parse.find_objects('interface Ethernet1/1')[0] >>> intf_cmd.linenum 1 >>> intf_cmd.parent >>> intf_cmd.children [, ] >>> >>> >>> addr_cmd = parse.find_objects('ip address 192.0.2.1')[0] >>> addr_cmd.linenum 2 >>> addr_cmd.parent >>> addr_cmd.children [] >>> ``` -------------------------------- ### Find Parent Lines using CLI Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md Use this CLI command to find parent configuration lines and their immediate children. It requires specifying the parent and child patterns. ```bash $ ccp parent -a 'router bgp,router-id' conf/path/or/file/glob.conf ``` -------------------------------- ### Find Parents Without Specific Child Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Shows how to find parent configuration objects that *do not* have a specific child command. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Find all interface objects that do NOT have an IP address configured interfaces_without_ip = parse.find_objects_wo_child(r"^interface", r"^ip address") for intf in interfaces_without_ip: print(f"Interface without IP: {intf.name}") ``` -------------------------------- ### Find Branches as Lists using CLI Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md Use this CLI command to find configuration branches, represented as lists of parent and child text lines. It requires specifying the branch patterns. ```bash $ ccp branch -a 'router bgp,address-family,default-information' conf/path/or/file/glob.conf ``` -------------------------------- ### Find Parents with Specific Child Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Demonstrates how to find parent configuration objects that have a specific child command using `find_parent_objects()`. ```python from ciscoconfparse import CiscoConfParse parse = CiscoConfParse("myconfig.conf") # Find all objects that have a child line containing 'ip helper-address' objects_with_helper = parse.find_parent_objects(r"ip helper-address") for obj in objects_with_helper: print(f"Object with helper address: {obj.name}") ``` -------------------------------- ### Parse Configuration and Retrieve Text from IOSCfgLine Object Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_parent_child.md Parses a configuration snippet and retrieves the configuration text from an IOSCfgLine object found using find_objects(). Requires importing CiscoConfParse. ```python from ciscoconfparse2.ciscoconfparse2 import CiscoConfParse parse = CiscoConfParse([ '!', 'interface Serial1/0', ' ip address 1.1.1.5 255.255.255.252' ]) for cmd in parse.find_objects(r"interface"): print("Object: " + repr(cmd)) print("Config text: " + cmd.text) quit() ``` -------------------------------- ### Access CiscoIOSInterface Components from CiscoRange Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_cisco_range.md Shows how to access individual CiscoIOSInterface objects from a CiscoRange and then use their attributes (slot, port, prefix) to get components of the interface. ```python >>> from ciscoconfparse2 import CiscoRange >>> >>> intf = CiscoRange("Ethernet1/3,10")[0] >>> intf >>> >>> intf.slot 1 >>> >>> intf.port 3 >>> >>> intf.prefix 'Ethernet' >>> ``` -------------------------------- ### Using BaseCfgLine as a String Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Shows how BaseCfgLine objects can be treated like strings for basic operations such as checking for substrings, splitting, and accessing elements. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse(['hostname Foo'], syntax='ios') >>> cmd = parse.find_objects('hostname')[0] >>> >>> cmd >>> cmd.linenum 0 >>> >>> # Use cmd with a sub-string match >>> 'Foo' in cmd True >>> >>> # Split cmd on whitespace like a string >>> cmd.split() ['hostname', 'Foo'] >>> >>> # Get the hostname using string manipulation >>> hostname = cmd.split()[-1] >>> hostname 'Foo' >>> ``` -------------------------------- ### Get ARP Timeout with Untyped Default using re_match_iter_typed() Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Use `untyped_default=True` to prevent the `default` value from being cast to the `result_type`. This is useful when the default value should remain a string. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse('short.conf') >>> intf_cmd = parse.find_objects(r'^interface\s+Vlan20$')[0] >>> arp_timeout = intf_cmd.re_match_iter_typed(r'arp\s+timeout\s+(\d+)', ... result_type=int, untyped_default=True, default='__no_explicit_value__') >>> arp_timeout '__no_explicit_value__' >>> ``` -------------------------------- ### Get ARP Timeout as Integer using re_match_iter_typed() Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Extract a value and cast it to a specific Python type using `result_type`. The `default` value is also cast to the specified `result_type`. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse('short.conf') >>> intf_cmd = parse.find_objects(r'^interface\s+Vlan10$')[0] >>> arp_timeout = intf_cmd.re_match_iter_typed(r'arp\s+timeout\s+(\d+)', ... result_type=int, default=4*3600) >>> arp_timeout 240 >>> ``` -------------------------------- ### Get Hostname using re_match_typed() Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Use `re_match_typed()` to extract a single typed value from a configuration object. Requires a capture group in the regex. The `default` parameter specifies a fallback value. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse('short.conf') >>> cmd = parse.find_objects(r'^hostname')[0] >>> hostname = cmd.re_match_typed(r'^hostname\s+(\S+)', default='') >>> hostname 'IAHS1MDF-AR01A' >>> ``` -------------------------------- ### Get Multiple DHCP Helper Addresses using re_list_iter_typed() Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Use `re_list_iter_typed()` to extract all matching values for a given regex from a configuration object. This method is suitable for retrieving multiple occurrences of a pattern. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse('short.conf') >>> >>> # Iterate over matching interfaces >>> intf_cmd = parse.find_objects(r'^interface\s+Vlan10$')[0] >>> retval = intf_cmd.re_list_iter_typed("ip helper-address (\S.*)") >>> retval ['198.51.100.12', '203.0.113.12'] >>> ``` -------------------------------- ### Execute Unit Tests Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Command to execute the unit tests for the ciscoconfparse2 project. ```bash pytest ``` -------------------------------- ### Get Hostname using re_match_iter_typed() Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_get_config_values.md Use `re_match_iter_typed()` to iterate over child objects and return the first matching typed value. This method simplifies extraction by handling the search internally. Requires a capture group in the regex. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse('short.conf') >>> hostname = parse.re_match_iter_typed(r'^hostname\s+(\S+)', default='') >>> hostname 'IAHS1MDF-AR01A' >>> ``` -------------------------------- ### Find Branches as Lists using Python API Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md This Python script demonstrates finding configuration branches as lists of text lines using the CiscoConfParse library. It iterates through branches and prints the text of each object within the branch. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse("conf/path/or/file/glob.conf") >>> for branch in parse.find_object_branches( ... ["router bgp", "address-family", "default-information"] ... ): ... print([obj.text for obj in branch]) ... >>> ``` -------------------------------- ### Find IP Addresses in CIDR Range Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md Use `ccp ipgrep` to find IP addresses within a specified CIDR range. By default, it splits words on whitespace and checks if a word is an IP address within the range. This example shows finding IPs in the '172.16.1.0/24' range from a file. ```bash $ ccp ipgrep -s 172.16.1.0/24 path/to/file.txt 172.16.1.1 172.16.1.1 172.16.1.2 $ ``` -------------------------------- ### Find Parent Objects using Python API Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md This Python script demonstrates how to find parent configuration objects using the CiscoConfParse library. It iterates through parent objects and prints their text. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse("conf/path/or/file/glob.conf") >>> for obj in parse.find_parent_objects(["router bgp"]): ... print(obj.text) ... >>> ``` -------------------------------- ### Find Parent Objects Without Specific Child Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/tutorial_parent_child.md Use `find_parent_objects_wo_child()` to find parent configuration lines that do *not* have a specific child configuration. This is useful for identifying configurations where a certain feature is enabled by default but not explicitly disabled. It requires a regex for the parent and a regex for the child to *exclude*. An example checks for interfaces that do not have CDP disabled. ```python >>> parse = CiscoConfParse("/tftpboot/bucksnort.conf") >>> if not bool(parse.find_objects(r'no cdp run')): ... cdp_intfs = parse.find_parent_objects_wo_child(r'^interface', ... r'no cdp enable') ``` ```python >>> cdp_intfs [, , ] ``` -------------------------------- ### Find Child Objects using Python API Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/cli.md This Python script shows how to find child configuration objects using the CiscoConfParse library. It searches for objects matching a list of parent and child patterns. ```python >>> from ciscoconfparse2 import CiscoConfParse >>> parse = CiscoConfParse("conf/path/or/file/glob.conf") >>> for obj in parse.find_child_objects( ... ["router bgp", "address-family", "default-information"] ... ): ... print(obj.text) ... >>> ``` -------------------------------- ### CiscoConfParse Object API Source: https://github.com/mpenning/ciscoconfparse2/blob/main/sphinx-doc/index.md Documentation for the main CiscoConfParse object, its methods, and attributes for parsing Cisco configuration files. ```APIDOC ## CiscoConfParse Object API ### Description This section details the `CiscoConfParse` object, which is the primary interface for parsing and manipulating Cisco configuration data. ### Endpoint N/A (This is a library API, not a web endpoint) ### Methods - **`__init__(self, conf_file)`**: Initializes the `CiscoConfParse` object with a configuration file. - **`find_objects(self, regex, parentspec=None, childspec=None)`**: Finds configuration lines matching a regex, optionally within a parent-child context. - **`find_objects_w_children(self, regex, childspec)`**: Finds configuration lines that have children matching a specific regex. - **`find_objects_wo_children(self, regex, childspec)`**: Finds configuration lines that do not have children matching a specific regex. - **`re_match_typed(self, regex, parentspec=None, childspec=None)`**: Returns a typed object matching the regex. - **`re_match_iter_typed(self, regex, parentspec=None, childspec=None)`**: Iterates over all typed objects matching the regex. - **`re_list_iter_typed(self, regex, parentspec=None, childspec=None)`**: Returns a list of typed objects matching the regex. ### Attributes - **`lines`**: A list of all configuration lines. - **`ios`**: A boolean indicating if the configuration is from an IOS device. ### Example Usage ```python from ciscoconfparse import CiscoConfParse # Assuming 'config.txt' contains Cisco configuration cfg = CiscoConfParse('config.txt') # Find all interface lines interfaces = cfg.find_objects(r'^interface') # Find all lines with 'ip address' under an interface for intf in interfaces: ip_addresses = intf.re_match_iter_typed(r'ip address (\S+)', childspec=r'^interface') for ip in ip_addresses: print(f"Interface: {intf.text}, IP Address: {ip.text}") ``` ```