ciscoconfparse2 functions
- ciscoconfparse2.initialize_ciscoconfparse2(read_only=False, debug=0) tuple[Dict[str, str], List[int]]
Initialize ciscoconfparse2 global variables and configure logging.
- ciscoconfparse2.cfgobj_from_text(text_list: List[str], txt: str, idx: int, syntax: str | None = None, comment_delimiters: List[str] | None = None, factory: bool | None = None) BaseCfgLine
Build a configuration object from configuration text, syntax, and factory inputs.
- Parameters:
text_list (List[str]) – The input list of text configuration strings
txt (str) – The specific configuration string to evaluate
txt – The specific configuration string to evaluate
idx (int) – Line-number to assign to the configuration object
syntax (str) – A valid configuration syntax
comment_delimiters (List[str]) – A sequence of string comment-delimiters
factory (bool) – Controls whether to read the configuration lines as a factory input
- Returns:
A configuration object appropriate for the configuration
- Return type:
- ciscoconfparse2.build_space_tolerant_regex(linespec: str, encoding: str = 'utf-8') str
Accept a string, and return a regex-like string with all spaces replaced with ‘s+’.
- ciscoconfparse2.convert_junos_to_ios(input_list: List[str] | None = None, stop_width: int = 4, comment_delimiters: List[str] | None = None, ignore_blank_lines: bool = False, debug: int = 0) List[str]
Accept input_list containing a list of junos-brace-formatted-string config lines. This method strips off semicolons / braces from the string lines in input_list and returns the lines in a new list where all lines are explicitly indented as IOS would (as if IOS understood braces).
- Parameters:
input_list (List[str]) – A sequence of brace-delimited configuration strings.
stop_width (int) – Integer representing the leading-spaces to indent levels of output child strings.
comment_delimiters (List[str]) – Sequence of string comment-delimiters
ignore_blank_lines (bool) – Whether to ignore blank lines, defaults to False
debug (int) – Debug level for this method
- Returns:
Indented configuration strings
- Return type:
List[str]
ciscoconfparse2.CiscoConfParse Object
- class ciscoconfparse2.CiscoConfParse(config: str | List[str] | tuple[str, ...] | None = None, syntax: str = 'ios', encoding: str = 'UTF-8', loguru: bool = True, comment_delimiters: List[str] | None = None, auto_indent_width: int = -1, linesplit_rgx: str = '\\r*\\n', ignore_blank_lines: bool = False, auto_commit: bool = True, factory: bool = False, debug: int = 0)
Parse Cisco IOS configurations and answer queries about the configs.
Initialize CiscoConfParse.
Note
comment_delimiters
always assumes the delimiter is one character wide.Note
ignore_blank_lines
changes the original ciscoconfparse default value.- Parameters:
config (Union[str,List[str],tuple[str, ...]]) – A list of configuration lines or the filepath to the configuration.
syntax (str) – The configuration type, default to ‘ios’; it must be one of: ‘ios’, ‘nxos’, ‘iosxr’, ‘asa’, ‘junos’. Use ‘junos’ for any brace-delimited network configuration (including F5, Palo Alto, etc…).
encoding (str) – The configuration encoding, default to
locale.getpreferredencoding()
.loguru (bool) – Control whether CiscoConfParse should enable
loguru
, default to True.comment_delimiters (List[str]) – String comment delimiters. This should only be changed when parsing non-Cisco configurations, which do not use a ‘!’ as the comment delimiter.
comment
defaults to ‘!’. This value can hold multiple characters in case the config uses multiple characters for comment delimiters.auto_indent_width (int) – Defaults to -1, and should be kept that way unless you’re working on a very tricky config parsing problem.
linesplit_rgx (str) – Used when parsing configuration files to find where new configuration lines are; it is best to leave this as the default, unless you’re working on a system that uses unusual line terminations (for instance something besides Unix, OSX, or Windows).
ignore_blank_lines (bool) – Defaults to False; when this is set True, ciscoconfparse2 ignores blank configuration lines.
auto_commit (bool) – Control whether CiscoConfParse should auto-commit config changes when possible, default to True. However, parsing very large configs may be faster with
auto_commit=False
.factory (bool) – Control whether CiscoConfParse should enable the beta-quality configuration parameter parser, default to False. factory parsing is only useful on IOS configs. Do not use factory to parse NXOS, IOS-XR, or Cisco ASA configurations.
debug (int) – Control CiscoConfParse debug output, default is 0.
- Returns:
A CiscoConfParse object
- Return type:
This example illustrates how to parse a simple Cisco IOS configuration with
CiscoConfParse
into a variable calledparse
. This example also illustrates what theconfig_objs
andioscfg
attributes contain.>>> from ciscoconfparse2 import CiscoConfParse >>> config = [ ... 'logging trap debugging', ... 'logging 172.28.26.15', ... ] >>> parse = CiscoConfParse(config=config) >>> parse <CiscoConfParse: 2 lines / syntax: ios / comment delimiter: '!' / factory: False> >>> parse.config_objs <ConfigList, comment='!', conf=[<IOSCfgLine # 0 'logging trap debugging'>, <IOSCfgLine # 1 'logging 172.28.26.15'>]> >>> parse.text ['logging trap debugging', 'logging 172.28.26.15'] >>>
Attributes
CiscoConfParse().objs is an alias for the CiscoConfParse().config_objs property.
Fix Py3.5 deprecation of universal newlines
comment_delimiters
(list) A list of strings containing the comment-delimiters. Default: [“!”]
config_objs
(
ConfigList
) A custom list, which contains all parsedIOSCfgLine
instances.debug
(int) An int to enable verbose config parsing debugs. Default 0.
ioscfg
(list) A list of text configuration strings
syntax
(str) A string holding the configuration type. Default: ‘ios’. Must be one of: ‘ios’, ‘nxos’, ‘iosxr’, ‘asa’, ‘junos’. Use ‘junos’ for any brace-delimited network configuration (including F5, Palo Alto, etc…).
- __eq__(other)
Method generated by attrs for class CiscoConfParse.
- __hash__ = None
- __ne__(other)
Method generated by attrs for class CiscoConfParse.
- __repr__() str
Return a string that represents this CiscoConfParse object instance. The number of lines embedded in the string is calculated from the length of the config_objs attribute.
- Returns:
A representation of this object.
- Return type:
- commit() None
Use
commit()
to manually fix upconfig_objs
relationships after modifying a parsed configuration. This method is slow; try to batch calls tocommit()
if possible.- Returns:
None
- Return type:
None
Warning
If you modify a configuration after parsing it with
CiscoConfParse
, you must callcommit()
orcommit()
before searching the configuration again with methods such asfind_objects()
. Failure to callcommit()
orcommit()
on config modifications could lead to unexpected search results.
- find_child_objects(parentspec, childspec=None, ignore_ws=False, recurse=True, escape_chars=False, reverse=False)
Parse through the children of all parents matching parentspec, and return a list of child objects, which matched the childspec.
- Parameters:
parentspec (str) – Text regular expression for the parent’s configuration line. A list is preferred.
childspec – Text regular expression for the child’s configuration line.
ignore_ws (bool) – Ignore whitespace, default to False
recurse (bool) – Control whether to recurse in the config, default to True.
escape_chars (bool) – Controls whether characters are escaped before searching, default to False.
reverse (bool) – Controls whether results are reversed; set True if modifying the configuration with these results.
- Returns:
Matching child objects
- Return type:
List[BaseCfgLine]
Warning
Do not set
childspec
if searching with a tuple of strings or list of strings.This example finds the object for “ge-0/0/1” under “interfaces” in the following config…
interfaces ge-0/0/0 unit 0 family ethernet-switching port-mode access vlan members VLAN_FOO ge-0/0/1 unit 0 family ethernet-switching port-mode trunk vlan members all native-vlan-id 1 vlan unit 0 family inet address 172.16.15.5/22
The following object should be returned:
<IOSCfgLine # 7 ' ge-0/0/1' (parent is # 0)>
We do this by quering
find_child_objects()
; we set our parent as^\s*interface
and set the child as^\s+ge-0/0/1
.>>> from ciscoconfparse2 import CiscoConfParse >>> config = ['interfaces', ... ' ge-0/0/0', ... ' unit 0', ... ' family ethernet-switching', ... ' port-mode access', ... ' vlan', ... ' members VLAN_FOO', ... ' ge-0/0/1', ... ' unit 0', ... ' family ethernet-switching', ... ' port-mode trunk', ... ' vlan', ... ' members all', ... ' native-vlan-id 1', ... ' vlan', ... ' unit 0', ... ' family inet', ... ' address 172.16.15.5/22', ... ] >>> p = CiscoConfParse(config=config) >>> p.find_child_objects(['interface', r'ge-0/0/1']) [<IOSCfgLine # 7 ' ge-0/0/1' (parent is # 0)>] >>>
- find_object_branches(branchspec: tuple[str, ...] | List[str] = (), regex_flags: RegexFlag | int = 0, regex_groups: bool = False, empty_branches: bool = False, reverse: bool = False, debug: int = 0) List[Any]
A branch is just a list of all matching parent and child text lines. This method iterates over a tuple of regular expression strings in branchspec and returns matching objects in a list of lists (consider it similar to a table of matching config objects). branchspec expects to start at a parent line and walk through the nested child lines below it (with no limit on depth).
Previous CiscoConfParse() methods only handled a single parent regex and single child regex (such as
find_objects()
).In comparison to other CiscoConfParse() ‘find’ methods, use this method to transcend past what could otherwise be complicated nested loops to include nested ‘branches’ statements in a single family (i.e. parents, children, grand-children, great-grand-children, etc). The result of handling longer regex chains is that it flattens nested loops in your scripts; this makes parsing heavily-nested configuratations like Juniper, Palo-Alto, and F5 much simpler. Of course, there are plenty of applications for normally “flatter” config formats like Cisco IOS.
Return a list of lists (of object ‘branches’) which are nested to the same depth required in branchspec. However, unlike most other CiscoConfParse() methods, return an explicit None if there is no object match. Returning None allows a single search over configs that may not be uniformly nested in every branch.
Warning
The
allow_none
from original ciscoconfparse is removed and no longer a configuration option; it will always be regarded as True.- Parameters:
branchspec (Union[tuple[str, ...],List[str]]) – Regular expressions to be matched.
regex_flags (Union[re.RegexFlags,int]) – Chained regular expression flags, such as re.IGNORECASE|re.MULTILINE
regex_groups (bool) – Return a tuple of re.Match groups instead of the matching configuration objects, default is False.
empty_branches (bool) – If True, return a list of None statements if there is no match; before version 1.9.49, this defaulted True.
reverse (bool) – If True, reverse the return value order.
debug (int) – Set > 0 for debug messages
- Returns:
A list of lists of matching
IOSCfgLine
objects- Return type:
List[List[BaseCfgLine]]
>>> from operator import attrgetter >>> from ciscoconfparse2 import CiscoConfParse >>> config = [ ... 'ltm pool FOO {', ... ' members {', ... ' k8s-05.localdomain:8443 {', ... ' address 192.0.2.5', ... ' session monitor-enabled', ... ' state up', ... ' }', ... ' k8s-06.localdomain:8443 {', ... ' address 192.0.2.6', ... ' session monitor-enabled', ... ' state down', ... ' }', ... ' }', ... '}', ... 'ltm pool BAR {', ... ' members {', ... ' k8s-07.localdomain:8443 {', ... ' address 192.0.2.7', ... ' session monitor-enabled', ... ' state down', ... ' }', ... ' }', ... '}', ... ] >>> parse = CiscoConfParse(config=config, syntax='junos', comment='#') >>> >>> branchspec = (r'ltm\spool', r'members', r'\S+?:\d+', r'state up') >>> branches = parse.find_object_branches(branchspec=branchspec) >>> >>> # We found three branches >>> len(branches) 3 >>> # Each branch must match the length of branchspec >>> len(branches[0]) 4 >>> # Print out one object 'branch' >>> branches[0] Branch(['ltm pool FOO', ' members', ' k8s-05.localdomain:8443', ' state up']) >>> >>> # Get the a list of text lines for this branch... >>> [ii.text for ii in branches[0]] ['ltm pool FOO', ' members', ' k8s-05.localdomain:8443', ' state up'] >>> >>> # Get the config text of the root object of the branch... >>> branches[0][0].text 'ltm pool FOO' >>> >>> # Note: `None` in branches[1][-1] because of no regex match >>> branches[1] Branch(['ltm pool FOO', ' members', ' k8s-06.localdomain:8443', None]) >>> >>> branches[2] Branch(['ltm pool BAR', ' members', ' k8s-07.localdomain:8443', None]) >>>
- find_objects(linespec: str | Pattern | BaseCfgLine | List[str] | List[Pattern], exactmatch: bool = False, ignore_ws: bool = False, escape_chars: bool = False, reverse: bool = False) List[BaseCfgLine]
Find all
IOSCfgLine
objects whose text matcheslinespec
and return theIOSCfgLine
objects in a python list.- Parameters:
linespec (Union[str,re.Pattern,BaseCfgLine, List[str], List[re.Pattern]]) – Text regular expression or a list with an expression for the
IOSCfgLine
objects to be matchedexactmatch (str) – When set True, this option requires
linespec
match the whole configuration line, instead of a portion of the configuration line, default to False.ignore_ws (bool) – Controls whether whitespace is ignored, default to False.
reverse (bool) – Controls whether the order of the results is reversed, default to False.
- Returns:
Matching
IOSCfgLine
objects.- Return type:
List[BaseCfgLine]
This example illustrates the use of
find_objects()
>>> from ciscoconfparse2 import CiscoConfParse >>> config = [ ... '!', ... 'interface Serial1/0', ... ' ip address 1.1.1.1 255.255.255.252', ... '!', ... 'interface Serial1/1', ... ' ip address 1.1.1.5 255.255.255.252', ... '!', ... ] >>> parse = CiscoConfParse(config=config) >>> >>> parse.find_objects(r'^interface') [<IOSCfgLine # 1 'interface Serial1/0'>, <IOSCfgLine # 4 'interface Serial1/1'>] >>>
- find_parent_objects(parentspec: str | Pattern | List[str], childspec: str | None = None, ignore_ws: bool = False, recurse: bool = True, escape_chars: bool = False, reverse: bool = False) List[BaseCfgLine]
Return a list of parent
IOSCfgLine
objects, which matched theparentspec
and whose children matchchildspec
. Only the parentIOSCfgLine
objects will be returned.- Parameters:
parentspec (Union[str,List[str],tuple[str, ...]]) – Text regular expression or a list of expressions for the
IOSCfgLine
object to be matchedchildspec (str) – Text regular expression for the child’s configuration line
ignore_ws (bool) – boolean that controls whether whitespace is ignored
recurse (bool) – Set True if you want to search all children (children, grand children, great grand children, etc…). This is considered True if parentspec is a list or tuple.
escape_chars (bool) – Set True if you want to escape characters before searching
reverse (bool) – Set True if you want to reverse the order of the results
- Returns:
A list of matching parent
IOSCfgLine
objects- Return type:
List[BaseCfgLine]
Warning
Do not set
childspec
if searching with a tuple of strings or list of strings.This example uses
find_parent_objects()
to find all ports that are members of access vlan 300 in following config…! interface FastEthernet0/1 switchport access vlan 532 spanning-tree vlan 532 cost 3 ! interface FastEthernet0/2 switchport access vlan 300 spanning-tree portfast ! interface FastEthernet0/3 duplex full speed 100 switchport access vlan 300 spanning-tree portfast !
The following interfaces should be returned:
interface FastEthernet0/2 interface FastEthernet0/3
We do this by quering find_objects_w_child(); we set our parent as ^interface and set the child as switchport access vlan 300.
>>> from ciscoconfparse2 import CiscoConfParse >>> config = ['!', ... 'interface FastEthernet0/1', ... ' switchport access vlan 532', ... ' spanning-tree vlan 532 cost 3', ... '!', ... 'interface FastEthernet0/2', ... ' switchport access vlan 300', ... ' spanning-tree portfast', ... '!', ... 'interface FastEthernet0/3', ... ' duplex full', ... ' speed 100', ... ' switchport access vlan 300', ... ' spanning-tree portfast', ... '!', ... ] >>> p = CiscoConfParse(config=config) >>> p.find_parent_objects(['interface', 'vlan 300']) [<IOSCfgLine # 5 'interface FastEthernet0/2'>, <IOSCfgLine # 9 'interface FastEthernet0/3'>] >>>
- find_parent_objects_wo_child(parentspec, childspec: str | None = None, ignore_ws: bool = False, recurse: bool = False, escape_chars: bool = False, reverse: bool = False)
Return a list of parent
IOSCfgLine
objects, which matched theparentspec
and whose children did not matchchildspec
. Only the parentIOSCfgLine
objects will be returned. For simplicity, this method only finds oldest_ancestors without immediate children that match.- Parameters:
- parentspecstr
Text regular expression for the
IOSCfgLine
object to be matched; this must match the parent’s line- childspecstr
Text regular expression for the line to be matched; this must match the child’s line
- ignore_wsbool
boolean that controls whether whitespace is ignored
- recursebool
boolean that controls whether to recurse through children of children
- escape_charsbool
boolean that controls whether to escape characters before searching
- reversebool
Set True if you want to reverse the order of the results
- Returns:
- list
A list of matching parent configuration lines
Examples
This example finds all ports that are autonegotiating in the following config…
! interface FastEthernet0/1 switchport access vlan 532 spanning-tree vlan 532 cost 3 ! interface FastEthernet0/2 switchport access vlan 300 spanning-tree portfast ! interface FastEthernet0/2 duplex full speed 100 switchport access vlan 300 spanning-tree portfast !
The following interfaces should be returned:
interface FastEthernet0/1 interface FastEthernet0/2
We do this by quering
find_parent_objects_wo_child()
; we set our parent as^interface
and set the child asspeed\s\d+
(a regular-expression which matches the word ‘speed’ followed by an integer).>>> from ciscoconfparse2 import CiscoConfParse >>> config = ['!', ... 'interface FastEthernet0/1', ... ' switchport access vlan 532', ... ' spanning-tree vlan 532 cost 3', ... '!', ... 'interface FastEthernet0/2', ... ' switchport access vlan 300', ... ' spanning-tree portfast', ... '!', ... 'interface FastEthernet0/3', ... ' duplex full', ... ' speed 100', ... ' switchport access vlan 300', ... ' spanning-tree portfast', ... '!', ... ] >>> p = CiscoConfParse(config=config) >>> p.find_parent_objects_wo_child(r'^interface', r'speed\s\d+') [<IOSCfgLine # 1 'interface FastEthernet0/1'>, <IOSCfgLine # 5 'interface FastEthernet0/2'>] >>>
- get_auto_indent_from_syntax(syntax: str | None = None) int
Return an auto indent for the ‘syntax’ string in question
- get_text() List[str]
- Returns:
All text configuration statements
- Return type:
List[str]
Warning
The original ciscoconfparse
ioscfg`@property has been renamed to ``get_text()
.
- handle_ccp_brace_syntax(tmp_lines: list | None = None, syntax: str | None = None) List[str]
Deal with brace-delimited syntax issues, such as conditionally discarding junos closing brace-lines.
- property objs: ConfigList[BaseCfgLine]
CiscoConfParse().objs is an alias for the CiscoConfParse().config_objs property.
- Returns:
All configuration objects.
- Return type:
List[BaseCfgLine]
- property openargs: Dict[str, str | None]
Fix Py3.5 deprecation of universal newlines
Note
Ref original ciscoconfparse Github issue #114; also see https://softwareengineering.stackexchange.com/q/298677/23144.
- re_match_iter_typed(regexspec, group=1, result_type=<class 'str'>, default='', untyped_default=False)
Use
regexspec
to search the root parents in the config and return the contents of the regular expression group, at the integergroup
index, cast asresult_type
; if there is no match,default
is returned.- Parameters:
- regexspecstr
A string or python compiled regular expression, which should be matched. This regular expression should contain parenthesis, which bound a match group.
- groupint
An integer which specifies the desired regex group to be returned.
group
defaults to 1.- result_typetype
A type (typically one of:
str
,int
,float
, orIPv4Obj
). All returned values are cast asresult_type
, which defaults tostr
.- defaultany
The default value to be returned, if there is no match. The default is an empty string.
- untyped_defaultbool
Set True if you don’t want the default value to be typed
- Returns:
result_type
The text matched by the regular expression group; if there is no match,
default
is returned. All values are cast asresult_type
. The default result_type is str.
Examples
This example illustrates how you can use
re_match_iter_typed()
to get the first interface name listed in the config.>>> import re >>> from ciscoconfparse2 import CiscoConfParse >>> config = [ ... '!', ... 'interface Serial1/0', ... ' ip address 1.1.1.1 255.255.255.252', ... '!', ... 'interface Serial2/0', ... ' ip address 1.1.1.5 255.255.255.252', ... '!', ... ] >>> parse = CiscoConfParse(config=config) >>> parse.re_match_iter_typed(r'interface\s(\S+)') 'Serial1/0' >>>
The following example retrieves the hostname from the configuration
>>> from ciscoconfparse2 import CiscoConfParse >>> config = [ ... '!', ... 'hostname DEN-EDGE-01', ... '!', ... 'interface Serial1/0', ... ' ip address 1.1.1.1 255.255.255.252', ... '!', ... 'interface Serial2/0', ... ' ip address 1.1.1.5 255.255.255.252', ... '!', ... ] >>> parse = CiscoConfParse(config=config) >>> parse.re_match_iter_typed(r'^hostname\s+(\S+)') 'DEN-EDGE-01' >>>
- re_search_children(regexspec, recurse=False)
Use
regexspec
to search for root parents in the config with text matching regex. If recurse is False, only root parent objects are returned. A list of matching objects is returned.This method is very similar to
find_objects()
(when recurse is True); however it was written in response to the use-case described in Github Issue #156.- Parameters:
- regexspecstr
A string or python regular expression, which should be matched.
- recursebool
Set True if you want to search all objects, and not just the root parents
- Returns:
- list
A list of matching
IOSCfgLine
objects which matched. If there is no match, an emptylist()
is returned.
- read_config(config: None | tuple[str, ...] | List[str] | str | Path) List[str]
Read config as a string, list, tuple or pathlib.Path
- Returns:
The output configuration
- Return type:
List[str]
- read_config_file(filepath: str | None = None, linesplit_rgx: str = '\\r*\\n') List[str]
Read the config lines from the filepath. Return the list of text configuration commands or raise an error.
- save_as(filepath)
Save a text copy of the configuration at
filepath
; this method uses the OperatingSystem’s native line separators (such as\r\n
in Windows).
ciscoconfparse2.Diff Object
- class ciscoconfparse2.Diff(old_config: str | List[str] | tuple[str, ...] = None, new_config: str | List[str] | tuple[str, ...] = None, syntax: str = 'ios')
Initialize Diff().
- Parameters:
old_config – A string or sequence containing text configuration statements representing the old config. Default value: None. If a filepath is provided, load the configuration from the file.
old_config – Union[str, List[str], tuple[str, …]]
new_config – A string or sequence containing text configuration statements representing the new config. Default value: None. If a filepath is provided, load the configuration from the file.
new_config – Union[str, List[str], tuple[str, …]]
syntax – The configuration type. Default: ‘ios’.
syntax – ciscoconfparse2.Diff
- __eq__(other)
Method generated by attrs for class Diff.
- __hash__ = None
- __ne__(other)
Method generated by attrs for class Diff.
- get_diff() List[str]
- Returns:
The list of required configuration statements to go from the old_config to the new_config
- Return type:
List[str]