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:

str

>>> 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

__contains__(arg: str) bool

Implement ‘arg in self’ for this class

__eq__(val)

Return self==value.

__gt__(val)

Return self>value.

__hash__() int
Returns:

A unique identifier for this object

Return type:

int

__iter__() str
__len__() int
__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]

all_lines: Any
property all_parents: List
Returns:

A sequence of all parent objects, not including this object

Return type:

List[BaseCfgLine]

all_text: Any
append_to_family(insertstr: str, indent: int = -1, auto_indent: bool = False) None

Append an IOSCfgLine object with insertstr 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 a carrier-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
!
>>>
blank_line_keep: bool
property brace_termination: str
Returns:

The brace termination string for this BaseCfgLine()

Return type:

str

child_indent: int
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 of insertstr relative to this object and auto_indent_width.

Return type:

int

property classname: str
Returns:

The class name of this object

Return type:

str

confobj: Any
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:

bool

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() with reverse=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:

int

property family_text

Return a list with this the text of this object, and with all children in the direct line.

feature: str
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:

dict

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'}
>>>
get_unique_identifier() int
Returns:

A unique number for the BaseCfgLine object

Return type:

int

has_child_with(linespec: str, all_children: bool = False)
Parameters:
  • linespec (str) – The string to search for

  • all_children (bool) – Whether to search all children (recursively)

Returns:

Whether linespec exists in any of children

Return type:

bool

property has_children: bool
Returns:

Whether this object has children

Return type:

bool

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:

int

property index

Alias index to linenum

insert_after(**kwargs)
insert_before(**kwargs)
property is_child
property is_comment: bool

Return True if the line is a comment

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:

bool

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:

int

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
line: str
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.

linenum: int
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:

str

parent: Any
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 of IOSCfgLine text and return a list of the contents of objects matching the regular expression group, at the integer group index, cast as result_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 if groupdict is None.

  • result_type (Type) – A type (typically one of: str, int, float, or IPv4Obj). Unless groupdict is specified, all returned values are cast as result_type, which defaults to str.

  • 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 the group, result_type and untyped_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 as result_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 of IPv6Obj() 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 the IOSCfgLine 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:

str

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 called netmask.

>>> 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 of IOSCfgLine text and return the contents of the regular expression group, at the integer group index, cast as result_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 if groupdict is None.

  • result_type (Type) – A type (typically one of: str, int, float, or IPv4Obj). Unless groupdict is specified, all returned values are cast as result_type, which defaults to str.

  • 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 the group, result_type and untyped_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 as result_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 an IPv4Obj() 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 the IOSCfgLine text and return the contents of the regular expression group, at the integer group index, cast as result_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 if groupdict is None.

  • result_type (Type) – A type (typically one of: str, int, float, or IPv4Obj). Unless groupdict is specified, all returned values are cast as result_type, which defaults to str.

  • 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 the group, result_type and untyped_default arguments.

Returns:

The text matched by the regular expression group; if there is no match, default is returned. All values are cast as result_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 as str(), and the slot will be cast as int().

>>> 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
>>>

Search IOSCfgLine with regex

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 for regex.

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 this IOSCfgLine.

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 empty list() is returned.

re_sub(regex, replacergx, re_flags=None)

Replace all strings matching linespec with replacestr in the IOSCfgLine object; however, if the IOSCfgLine text matches ignore_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 matches ignore_rgx. ignore_rgx defaults to None, which means no lines matching regex are skipped.

Returns:
str

The new text after replacement

Examples

This example illustrates how you can use re_sub() to replace Serial1 with Serial0 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 with after

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:

str

replace_text(before, after, count=-1) str

String replace before with after

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:

str

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:

str

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-place

Note

The original text in this object will be unmodified.

Parameters:
  • sep (str) – Split text on the sep characters (by default, any whitespace)

  • maxsplit (int) – Maximum number of splits, default is -1 (no limit)

Returns:

A sequence of strings

Return type:

List[str]

strip(chars: str = None) str

Implement strip() on the BaseCfgLine().text

Note

The original text in this object will be unmodified.

Returns:

The stripped text

Return type:

str

property text: str
Returns:

Configuration text

Return type:

str

property verbose: str
Returns:

A string representation of this object

Return type:

str