Package: ciscoconfparse2
ciscoconfparse2Introduction: What is ciscoconfparse2?Summaryciscoconfparse2is similar to an advanced grep and diff that
specializes in network configuration files (such as those from Cisco,
Juniper, Palo Alto, etc); it is the next generation ofciscoconfparse, which was the primary development package
from 2007 until 2023.Simple UsageThe following code will parse a configuration stored intests/fixtures/configs/sample_02.iosand select interfaces that are shutdown.In this case, the parent is a line containinginterfaceand the child is a
line containing the wordshutdown.# filename: example.pyfromciscoconfparse2importCiscoConfParse############################################################################### Find all Cisco IOS interface names that are shutdown################################################################################ Search for:#     !#     interface Foo#      description ignore-this-line#      shutdown#     !# Search a configuration in the test fixutres directoryparse=CiscoConfParse('tests/fixtures/configs/sample_02.ios',syntax='ios')# Find a parent line containing 'interface' and child line with 'shutdown'forintf_objinparse.find_parent_objects(['interface','shutdown']):intf_name=" ".join(intf_obj.split()[1:])print(f"Shutdown:{intf_name}")That will print:$ python example.py
Shutdown: FastEthernet0/7
Shutdown: FastEthernet0/8
Shutdown: FastEthernet0/9
Shutdown: FastEthernet0/11
Shutdown: FastEthernet0/13
Shutdown: FastEthernet0/15
Shutdown: FastEthernet0/17
Shutdown: FastEthernet0/19
Shutdown: FastEthernet0/20
Shutdown: FastEthernet0/22
Shutdown: VLAN1Complex ExampleThe following code will parse a configuration stored intests/fixtures/configs/sample_08.iosand will find the
IP address / switchport parameters assigned to interfaces.fromciscoconfparse2importCiscoConfParsefromciscoconfparse2importIPv4Objdefintf_csv(intf_obj:str)->str:""":return: CSV for each interface object.:rtype: str"""intf_name=" ".join(intf_obj.split()[1:])# Use a string split() method from the BaseCfgLine()admin_status=intf_obj.re_match_iter_typed("^\s+(shutdown)",default="not_shutdown",result_type=str)# Search children of all interfaces for a regex match and return# the value matched in regex match group 1.  If there is no match,# return a default value: 0.0.0.1/32addr_netmask=intf_obj.re_match_iter_typed(r"^\s+ip\saddress\s(\d+\.\d+\.\d+\.\d+\s\S+)",result_type=IPv4Obj,group=1,default=IPv4Obj("0.0.0.1/32"))# Find the description and replace all commas in itdescription=intf_obj.re_match_iter_typed("description\s+(\S.*)").replace(",","_")switchport_status=intf_obj.re_match_iter_typed("(switchport)",default="not_switched")# Return a csv based on whether this is a switchportifswitchport_status=="not_switched":returnf"{intf_name},{admin_status},{addr_netmask.as_cidr_addr},{switchport_status},,,{description}"else:# Only calculate switchport values if this is a switchporttrunk_access=intf_obj.re_match_iter_typed("switchport mode (trunk)",default="access",result_type=str)access_vlan=intf_obj.re_match_iter_typed("switchport access vlan (\d+)",default=1,result_type=int)returnf"{intf_name},{admin_status},,{switchport_status},{trunk_access},{access_vlan},{description}"parse=CiscoConfParse('tests/fixtures/configs/sample_08.ios',syntax='ios')# Find interface BaseCfgLine() instances...forintf_objinparse.find_objects('^interface'):print(intf_csv(intf_obj))That will print:$ python example.py
Loopback0,not_shutdown,172.16.0.1/32,not_switched,,,SEE http://www.cymru.com/Documents/secure-ios-template.html
Null0,not_shutdown,0.0.0.1/32,not_switched,,,
ATM0/0,not_shutdown,0.0.0.1/32,not_switched,,,
ATM0/0.32 point-to-point,not_shutdown,0.0.0.1/32,not_switched,,,
FastEthernet0/0,not_shutdown,172.16.2.1/24,not_switched,,,[IPv4 and IPv6 desktop / laptop hosts on 2nd-floor North LAN]
FastEthernet0/1,not_shutdown,172.16.3.1/30,not_switched,,,[IPv4 and IPv6 OSPF Transit via West side of building]
FastEthernet1/0,not_shutdown,172.16.4.1/30,not_switched,,,[IPv4 and IPv6 OSPF Transit via North side of building]
FastEtheret1/1,not_shutdown,,switchport,access,12,[switchport to the comptroller cube]
FastEtheret1/2,not_shutdown,,switchport,access,12,[switchport to the IDF media converter]
Virtual-Template1,not_shutdown,0.0.0.1/32,not_switched,,,
Dialer1,not_shutdown,0.0.0.1/32,not_switched,,,[IPv4 and IPv6 OSPF Transit via WAN Dialer: NAT_ CBWFQ interface]Cisco IOS Factory UsageCiscoConfParse has a special feature that abstracts common IOS / NXOS / ASA / IOS XR fields; at this time, it is only supported on those configuration types. You will see factory parsing in CiscoConfParse code as parsing the configuration withfactory=True.Whyciscoconfparse2is aPythonlibrary
that helps you quickly answer questions like these about your
Cisco configurations:What interfaces are shutdown?Which interfaces are in trunk mode?What address and subnet mask is assigned to each interface?Which interfaces are missing a critical command?Is this configuration missing a standard config line?It can help you:Audit existing router / switch / firewall / wlc configurationsModify existing configurationsBuild new configurationsSpeaking generally, the library examines an IOS-style config and breaks
it into a set of linked parent / child relationships. You can perform
complex queries about these relationships.What changed in ciscoconfparse2?In late 2023, I started a rewrite becauseciscoconfparseis too large
and has some defaults that I wish it didn't have.  I frozeciscoconfparsePYPI releases atversion 1.9.41; there will be no
moreciscoconfparsePYPI releases.What do you do?  Upgrade tociscoconfparse2!Here's why, it:Streamlines the API towards a simpler user interface.Removes legacy and flawed methods from the original (this could be a breaking change for old scripts).Adds string methods toBaseCfgLine()objectsDefaultsignore_blank_lines=False(this could be a breaking change for old scripts).Is better at handling multiple-child-level configurations (such as IOS XR and JunOS)Can search for parents and children using anarbitrary list of ancestorsAdds the concept of change commits; this is a config-modification safety feature thatciscoconfparselacksAdds anauto_commitkeyword, which defaults TrueDocuments much more of the APIIntentionally requires a different import statement to minimize confusion between the original andciscoconfparse2Vasly improves Cisco IOS diffsWhat if we don't use Cisco IOS?In many cases, you can parsebrace-delimited configurationsinto a Cisco IOS style (seeoriginal ciscoconfparse Github Issue #17), which means that CiscoConfParse may be able to parse these configurations:Juniper Networks Junos OSPalo Alto Networks Firewall configurationsF5 Networks configurations (known caveats)CiscoConfParse also handles anything that has a Cisco IOS style of configuration, which includes:Cisco IOS, Cisco Nexus, Cisco IOS-XR, Cisco IOS-XE, Aironet OS, Cisco ASA, Cisco CatOSArista EOSBrocadeHP SwitchesForce 10 SwitchesDell PowerConnect SwitchesExtreme NetworksEnterasysScreenosDocsThe latest copy of the docs arearchived on the webInstallation and DownloadsUsepoetryfor Python3.x... :python -m pip install ciscoconfparse2What is the pythonic way of handling script credentials?Never hard-code credentialsUsepython-dotenvIs this a tool, or is it artwork?That depends on who you ask.  Many companies use CiscoConfParse as part of their
network engineering toolbox; others regard it as a form of artwork.Pre-requisitesThe ciscoconfparse2 python packagerequires Python versions 3.7+.Type-hinting (work-in-progress) targets Python3.9+ due to the need fortuple[str, ...]hints.Other ResourcesDive into Python3is a good way to learn PythonTeam CYMRUhas aSecure IOS Template, which is especially useful for external-facing routers / switchesCisco's Guide to hardening IOS devicesCenter for Internet Security Benchmarks(An email address, cookies, and javascript are required)Are you releasing licensing besides GPLv3?I will not. however, if it's truly a problem for your company, there are commercial solutions available (to include purchasing the project, or hiring me).Bug Tracker and SupportPlease report any suggestions, bug reports, or annoyances with agithub bug report.If you're having problems with general python issues, consider searching for a solution onStack Overflow.  If you can't find a solution for your problem or need more help, you canask on Stack Overfloworreddit/r/Python.If you're having problems with your Cisco devices, you can contact:Cisco TACreddit/r/Ciscoreddit/r/networkingNetworkEngineering.seDependenciesPython 3attrspasslibtomlkitdnspythonhier_configPyYAMLpyparsingtypeguardloguruUnit-Tests and DevelopmentWe are manually disabling someSonarCloudalerts with:#pragma warning disable S1313#pragma warning restore S1313WhereS1313is a False-positive thatSonarCloudflagsThose#pragma warninglines should be carefully-fenced to ensure that we don't disable aSonarCloudalert that is useful.Semantic Versioning and Conventional CommitsAt this point,ciscoconfparse2does NOT adhere toSemantic VersioningAlthough we addedcommitizenas a dev dependency, we are NOT enforcing commit rules (such asConventional Commits) yet.Execute Unit testsThe project'stest workflowchecks ciscoconfparse2 on Python versions 3.7 and higher, as well as apypy JITexecutable.If you already git cloned the repo and want to manually run tests either run withmake testfrom the base directory, or manually run withpytestin a unix-like system...$cdtests
$pytest./test*py
...Execute Test Coverage Line-Miss ReportIf you already have havepytestandpytest-covinstalled, run a test line miss report as shown below.$# Install the latest ciscoconfparse2$# (assuming the latest code is on pypi)$pipinstall-Uciscoconfparse2
$pipinstall-Upytest-cov
$cdtests
$pytest--cov-report=term-missing--cov=ciscoconfparse2./
...Editing the PackageThis uses the example of editing the package on a git branch calleddevelop...git clone https://github.com/mpenning/ciscoconfparse2cd ciscoconfparse2git branch developgit checkout developAdd / modify / delete on thedevelopbranchmake testIf tests run clean,git commitall the pending changes on thedevelopbranchIf you plan to publish this as an official version rev, edit the version number inpyproject.toml.  In the future, we want to integratecommitizento manage versioning.git checkout maingit merge developmake testgit push origin mainmake pypiSphinx DocumentationBuilding the ciscoconfparse2 documentation tarball comes down to this one wierd trick:cd sphinx-doc/pip install -r ./requirements.txt;  # install Sphinx dependenciespip install -r ../requirements.txt; # install ccp dependenciesmake htmlLicense and Copyrightciscoconfparse2is licensedGPLv3Copyright (C) 2023-2024 David Michael PenningtonThe word "Cisco" is a registered trademark ofCisco Systems.Authorciscoconfparse2was written byDavid Michael Pennington.