ccp_abc functions
- ciscoconfparse2.ccp_abc.get_brace_termination(line: str) str
Get the brace termination string from the
line
parameter.- Returns:
The brace termination string for this
line
.- Return type:
>>> get_brace_termination("http { }") '{ }' >>> >>> get_brace_termination("ltm virtual ACME { ") '{' >>> get_brace_termination(" } ") '}' >>>
ciscoconfparse2.ccp_abc
- class ciscoconfparse2.ccp_abc.BaseCfgLine(all_lines=None, line='__undefined__', **kwargs)
Base configuration object for all configuration line instances; in most cases, the configuration line will be a subclass of this object.
Accept an IOS line number and initialize family relationship attributes
- __eq__(val)
Return self==value.
- __gt__(val)
Return self>value.
- __hash__() int
- Returns:
A unique identifier for this object
- Return type:
Note
Also see
BaseCfgLine.get_unique_identifier()
.
- __lt__(val)
Return self<value.
- __repr__()
Return repr(self).
- __str__()
Return str(self).
- add_parent(**kwargs)
- property all_children: List
- Returns:
A sequence of all child objects, not including this object
- Return type:
List[BaseCfgLine]
- property all_parents: List
- Returns:
A sequence of all parent objects, not including this object
- Return type:
List[BaseCfgLine]
- append_to_family(insertstr: str, indent: int = -1, auto_indent: bool = False) None
Append an
IOSCfgLine
object withinsertstr
as a child at the top of the current configuration family.insertstr
is inserted at the end of the family to ensure there are no unintended object relationships created during the change.- Parameters:
insertstr (str) – The text configuration to be appended
indent (int) – The text configuration to be appended, default to -1
auto_indent (bool) – Automatically indent the child to
auto_indent_width
- Returns:
None
- Return type:
None
This example illustrates how you can use
append_to_family()
to add acarrier-delay
to each interface.>>> 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) >>> >>> for obj in parse.find_objects(r'^interface', reverse=True): ... obj.append_to_family(' carrier-delay msec 500') ... >>> >>> for line in parse.text: ... print(line) ... ! interface Serial1/0 ip address 1.1.1.1 255.255.255.252 carrier-delay msec 500 ! interface Serial1/1 ip address 1.1.1.5 255.255.255.252 carrier-delay msec 500 ! >>>
- property brace_termination: str
- Returns:
The brace termination string for this BaseCfgLine()
- Return type:
- property children
Return the direct children of this object
- classify_family_indent(insertstr: str = None) int
Look at the indent level of insertstr and return an integer for the auto_indent_width of insertstr relative to this object and auto_indent_width.
If insertstr is indented at the same level, return 0.
If insertstr is indented more, return a positive integer for how many
auto_indent_width
indents.If insertstr is indented less, return a negative integer for how many
auto_indent_width
indents.If insertstr is not indented on an integer multiple of
auto_indent_width
, raise NotImplementedError.
- Returns:
An integer for the
auto_indent_width
ofinsertstr
relative to this object andauto_indent_width
.- Return type:
- delete() bool
Delete this object, including from references in lists of child objects. By default, if a parent object is deleted, the child objects are also deleted.
- Returns:
Whether the delete operation was a success.
- Return type:
Note
When deleting objects, delete from the bottom of the configuration and work toward the beginning. Failure to do this could result in a
ConfigListItemDoesNotExist()
error.Failure to commit after deleting objects will delete the object, but it leaves line number gaps.
This example will delete all child objects; when deleting multiple objects, you should call
ciscoconfparse2.CiscoConfParse.find_objects()
withreverse=True
.>>> from ciscoconfparse2 import CiscoConfParse >>> config = ['a', ' child-b', 'c', ' child-d'] >>> parse = CiscoConfParse(config) >>> for obj in parse.find_objects(r"child", reverse=True): ... obj.delete() >>> parse.get_text() ['a', 'c'] >>>
- property dna
- property family_endpoint: int
- Returns:
The line number of the last child (or grandchild, etc)
- Return type:
- property family_text
Return a list with this the text of this object, and with all children in the direct line.
- property geneology
Iterate through to the oldest ancestor of this object, and return a list of all ancestors’ objects in the direct line as well as this obj. Cousins or aunts / uncles are not returned.
Note
Children of this object are not returned.
- property geneology_text
Iterate through to the oldest ancestor of this object, and return a list of all ancestors’ .text field for all ancestors in the direct line as well as this obj. Cousins or aunts / uncles are not returned.
Note
Children of this object are not returned.
- get_regex_typed_dict(regex: Match = None, type_dict: dict = None, default: str = None, debug: bool = False) dict
- Returns:
Return a typed dict if
regex
is an re.Match() instance (with named match groups) and type_dict is a dict of types. If a key in type_dict does not match, default is returned for that key.- Return type:
These examples demonstrate how
get_regex_typed_dict()
works.>>> _uut_regex = r"^(?P<my_digit>[\d+])(?P<no_digit>[^\d+])" >>> _type_dict = {"my_digit", int, "no_digit": str} >>> _default = "_no_match" >>> get_regex_typed_dict(re.search(_uut_regex, "1a"), type_dict=_type_dict, default=_default) {'my_digit': 1, 'no_digit': 'a'} >>> get_regex_typed_dict(re.search(_uut_regex, "a1"), type_dict=_type_dict, default=_default) {'my_digit': '_no_match', 'no_digit': '_no_match'} >>> get_regex_typed_dict(re.search(_uut_regex, ""), type_dict=_type_dict, default=_default) {'my_digit': '_no_match', 'no_digit': '_no_match'} >>>
- property hash_children
Return a unique hash of all children (if the number of children > 0)
- property indent: int
- Returns:
Padding of the number of left spaces of the
text
property- Return type:
- property index
Alias index to linenum
- insert_after(**kwargs)
- insert_before(**kwargs)
- property is_child
- property is_config_line: bool
Return a boolean for whether this is a config statement; returns False
- Returns:
Whether this object is a config line, blank line, or a comment.
- Return type:
- property is_intf
subclasses will override this method
- classmethod is_object_for(line='')
- property is_parent
- property is_subintf
subclasses will override this method
- property is_switchport
subclasses will override this method
- property last_family_linenum: int
- Returns:
Iterate through the family and find the last linenumber of the last family member. Return this object’s linenumber if there are no siblings.
- Return type:
If this family was parsed, return 3 (index of the last family member)
first (idx: 0) first-child (idx: 1) first-child-child (idx: 2) second (idx: 3) <-- return this index number
If this family was parsed, return 3 (index of the last family member)
first (idx: 0) second (idx: 1) second-child (idx: 2) second-child-child (idx: 3) <-- return this index number
- property lineage
Iterate through to the oldest ancestor of this object, and return a list of all ancestors / children in the direct line. Cousins or aunts / uncles are not returned.
Note
All children of this object are returned.
- lstrip(chars: str = None) str
Implement lstrip() on the BaseCfgLine().text
Note
The original
text
in this object will be unmodified.- Returns:
The stripped
text
- Return type:
- re_list_iter_typed(regex: str | ~re.Pattern, group: int = 1, result_type: type = <class 'str'>, groupdict: dict = None, recurse: bool = True, debug: bool = False) List[Any]
Use
regex
to search the children ofIOSCfgLine
text and return a list of the contents of objects matching the regular expression group, at the integergroup
index, cast asresult_type
; if there is no match, default to an empty list.- Parameters:
regex (Union[str, re.Pattern]) – A string or python compiled regular expression, which should be matched. This regular expression should contain parenthesis, which are bound to a match group.
group (int) – Specify the desired regex group to be returned.
group
defaults to 1; this is only used ifgroupdict
is None.result_type (Type) – A type (typically one of:
str
,int
,float
, orIPv4Obj
). Unlessgroupdict
is specified, all returned values are cast asresult_type
, which defaults tostr
.recurse (bool) – Set True if you want to search all children (children, grand children, great grand children, etc…), default to True.
groupdict (dict) – Set to a dict of types if you want to match on regex group names;
groupdict
overrides thegroup
,result_type
anduntyped_default
arguments.debug (bool) – Set True if you want to debug
re_list_iter_typed()
activity
- Returns:
The text matched by the regular expression group; if there is no match,
default
is returned. All values are cast asresult_type
, unless untyped_default is True.- Return type:
Any
Note
This loops through the children (in order) and returns a list of all matched text
This example illustrates how you can use
re_list_iter_typed()
to build a list ofIPv6Obj()
address objects for each interface.>>> import re >>> from ciscoconfparse2 import CiscoConfParse >>> from ciscoconfparse2.ccp_util import IPv6Obj >>> config = [ ... '!', ... 'interface Serial1/0', ... ' ip address 1.1.1.1 255.255.255.252', ... ' ipv6 address dead:beef::11/64', ... ' ipv6 address dead:beef::12/64', ... '!', ... 'interface Serial2/0', ... ' ip address 1.1.1.5 255.255.255.252', ... ' ipv6 address dead:beef::21/64', ... ' ipv6 address dead:beef::22/64', ... '!', ... ] >>> parse = CiscoConfParse(config) >>> obj = parse.find_objects(r"interface Serial1/0")[0] >>> obj.text interface Serial1/0 >>> addr_objs = obj.re_list_iter_typed(r"ipv6\s+address\s+(\S.+)", result_type=IPv6Obj) >>> print(obj.text, addr_objs) interface Serial1/0 [<IPv6Obj dead:beef::11/64>, <IPv6Obj dead:beef::12/64>] >>>
- re_list_iter_typed_groupdict_dict(regex: str | ~re.Pattern, group: int = 1, result_type: type = <class 'str'>, groupdict: dict = None, recurse: bool = True, debug: bool = False)
- re_list_iter_typed_groupdict_none(regex: str | ~re.Pattern, group: int = 1, result_type: type = <class 'str'>, groupdict: dict = None, recurse: bool = True, debug: bool = False)
- re_match(regex, group=1, default='')
Use
regex
to search theIOSCfgLine
text and return the regular expression group, at the integer index.- Parameters:
regex (str) – A string or python regular expression, which should be matched. This regular expression should contain parenthesis, which bound a match group.
group (int) – An integer which specifies the desired regex group to be returned, defaults to 1.
default (str) – The default value to be returned, if there is no match. By default an empty string is returned if there is no match.
- Returns:
The text matched by the regular expression group; if there is no match,
default
is returned.- Return type:
This example illustrates how you can use
re_match()
to store the mask of the interface which owns “1.1.1.5” in a variable callednetmask
.>>> 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) >>> >>> for obj in parse.find_objects(r'ip\saddress'): ... netmask = obj.re_match(r'1\.1\.1\.5\s(\S+)') >>> >>> print("The netmask is", netmask) The netmask is 255.255.255.252 >>>
- re_match_iter_typed(regex: str | ~re.Pattern, group: int = 1, result_type: type = <class 'str'>, default: ~typing.Any = '', untyped_default: bool = False, groupdict: dict = None, recurse: bool = True, debug: bool = False) Any
Use
regex
to search the children ofIOSCfgLine
text 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:
regex (Union[str, re.Pattern]) – A string or python compiled regular expression, which should be matched. This regular expression should contain parenthesis, which are bound to a match group.
group (int) – Specify the desired regex group to be returned.
group
defaults to 1; this is only used ifgroupdict
is None.result_type (Type) – A type (typically one of:
str
,int
,float
, orIPv4Obj
). Unlessgroupdict
is specified, all returned values are cast asresult_type
, which defaults tostr
.default (Any) – The default value to be returned, if there is no match.
recurse (bool) – Set True if you want to search all children (children, grand children, great grand children, etc…), default to True.
untyped_default (bool) – Set True if you don’t want the default value to be typed; this is only used if
groupdict
is None.groupdict (dict) – Set to a dict of types if you want to match on regex group names;
groupdict
overrides thegroup
,result_type
anduntyped_default
arguments.debug (bool) – Set True if you want to debug
re_match_iter_typed()
activity
- Returns:
The text matched by the regular expression group; if there is no match,
default
is returned. All values are cast asresult_type
, unless untyped_default is True.- Return type:
Any
Note
This loops through the children (in order) and returns when the regex hits its first match.
This example illustrates how you can use
re_match_iter_typed()
to build anIPv4Obj()
address object for each interface.>>> import re >>> from ciscoconfparse2 import CiscoConfParse >>> from ciscoconfparse2.ccp_util import IPv4Obj >>> 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) >>> obj = parse.find_objects(r"interface Serial1/0")[0] >>> obj.text interface Serial1/0 >>> addr_obj = obj.re_match_iter_typed(r"ip\s+address\s+(\d.+)", result_type=IPv4Obj) >>> print(obj.text, addr_obj) interface Serial1/0 <IPv4Obj 1.1.1.1/30> >>>
- re_match_typed(regex: str | ~re.Pattern, group: int = 1, result_type: type = <class 'str'>, default: ~typing.Any = '', untyped_default: bool = False, groupdict: dict = None) Any
Use
regex
to search theIOSCfgLine
text 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:
regex (Union[str, re.Pattern]) – A string or python compiled regular expression, which should be matched. This regular expression should contain parenthesis, which are bound to a match group.
group (int) – Specify the desired regex group to be returned.
group
defaults to 1; this is only used ifgroupdict
is None.result_type (Type) – A type (typically one of:
str
,int
,float
, orIPv4Obj
). Unlessgroupdict
is specified, all returned values are cast asresult_type
, which defaults tostr
.default (Any) – The default value to be returned, if there is no match.
untyped_default (bool) – Set True if you don’t want the default value to be typed; this is only used if
groupdict
is None.groupdict (dict) – Set to a dict of types if you want to match on regex group names;
groupdict
overrides thegroup
,result_type
anduntyped_default
arguments.
- Returns:
The text matched by the regular expression group; if there is no match,
default
is returned. All values are cast asresult_type
, unless untyped_default is True.- Return type:
Any
This example illustrates how you can use
re_match_typed()
to build an association between an interface name, and its numerical slot value. The name will be cast asstr()
, and the slot will be cast asint()
.>>> 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) >>> >>> slots = dict() >>> for obj in parse.find_objects(r'^interface'): ... name = obj.re_match_typed(regex=r'^interface\s(\S+)', ... default='UNKNOWN') ... slot = obj.re_match_typed(regex=r'Serial(\d+)', ... result_type=int, ... default=-1) ... print("Interface {0} is in slot {1}".format(name, slot)) ... Interface Serial1/0 is in slot 1 Interface Serial2/0 is in slot 2 >>>
- re_search(regex, default='', debug=0)
Search
IOSCfgLine
withregex
- Parameters:
- regexstr
A string or python regular expression, which should be matched.
- defaultstr
A value which is returned if
re_search()
doesn’t find a match while looking forregex
.
- Returns:
- str
The
IOSCfgLine
text which matched. If there is no match,default
is returned.
- re_search_children(regex, recurse=False)
Use
regex
to search the text contained in the children of thisIOSCfgLine
.- Parameters:
- regexstr
A string or python regular expression, which should be matched.
- recursebool
Set True if you want to search all children (children, grand children, great grand children, etc…)
- Returns:
- list
A list of matching
IOSCfgLine
objects which matched. If there is no match, an emptylist()
is returned.
- re_sub(regex, replacergx, re_flags=None)
Replace all strings matching
linespec
withreplacestr
in theIOSCfgLine
object; however, if theIOSCfgLine
text matchesignore_rgx
, then the text is not replaced.- Parameters:
- regexstr
A string or python regular expression, which should be matched.
- replacergxstr
A string or python regular expression, which should replace the text matched by
regex
.- ignore_rgxstr
A string or python regular expression; the replacement is skipped if
IOSCfgLine
text matchesignore_rgx
.ignore_rgx
defaults to None, which means no lines matchingregex
are skipped.
- Returns:
- str
The new text after replacement
Examples
This example illustrates how you can use
re_sub()
to replaceSerial1
withSerial0
in a configuration…>>> 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) >>> >>> for obj in parse.find_objects('Serial'): ... print("OLD {}".format(obj.text)) ... obj.re_sub(r'Serial1', r'Serial0') ... print(" NEW {}".format(obj.text)) OLD interface Serial1/0 NEW interface Serial0/0 OLD interface Serial1/1 NEW interface Serial0/1 >>>
- replace(before, after, count=-1) str
String replace
before
withafter
If the optional argument count is given, only the first count occurrences are replaced.
Note
The original
text
in this object will be unmodified.- Returns:
The replaced config string
- Return type:
- replace_text(before, after, count=-1) str
String replace
before
withafter
If the optional argument count is given, only the first count occurrences are replaced.
This method is substantially faster than
BaseCfgLine().re_sub()
for a similar replace operation.Note
This will replace the config tex string in-place.
- Returns:
The replaced config string
- Return type:
- rstrip(chars: str = None) str
Implement rstrip() on the BaseCfgLine().text
Note
The original
text
in this object will be unmodified.- Returns:
The stripped
text
- Return type:
- safe_escape_curly_braces(text)
Escape curly braces in strings since they could be misunderstood as f-string or string.format() delimiters…
If BaseCfgLine receives line with curly-braces, this method can escape the curly braces so they are not mis-interpreted as python string formatting delimiters.
- property siblings
- split(sep: str = None, maxsplit: int = -1) List[str]
Split
text
in-placeNote
The original
text
in this object will be unmodified.