ciscoconfparse2.models_cisco

class ciscoconfparse2.models_cisco.TrackingInterface(grp: int, intf: BaseCfgLine, decr: int = 0, weight: int = None)

Implement a TrackingInterface() object for Cisco IOS HSRP, GLBP and VRRP

__contains__(arg: str) bool

Implement ‘arg in self’ for this class

__eq__(other)

Return True or False based on whether this Tracking interface is equal to the other instance; both instances must be a TrackingInterface() instance to compare True

__gt__(val)

Return self>value.

__hash__()

Return a hash value based on the Tracking interface group, interface name and decrement / weighting.

__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
decr: int
property decrement

Return an integer with the TrackingInterface() decrement or None if there is no decrement.

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

property group
grp: 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 interface
property interface_name

Return the interface name as a string, or return None

intf: BaseCfgLine
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

property name
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 tracking_interface_group

Return an integer with the TrackingInterface() Group

property verbose: str
Returns:

A string representation of this object

Return type:

str

weight: int
property weighting

Return the weighting (ref GLBP) integer value.

class ciscoconfparse2.models_cisco.HSRPInterfaceGroup(grp=0, parent_obj=None)

A HSRP Interface Group object

__contains__(arg: str) bool

Implement ‘arg in self’ for this class

__eq__(other)

Return True if this HSRPInterfaceGroup() is equal to the other instance or False if the other instance is not an HSRPInterfaceGroup().

__gt__(val)

Return self>value.

__hash__()

Return a hash for this HSRPInterfaceGroup() instance.

__iter__() str
__len__() int
__lt__(val)

Return self<value.

__repr__()

Return repr(self).

__str__()

Return a string representation of this HSRPInterfaceGroup() instance.

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
!
>>>
property authentication_md5_keychain

Return the string text of the MD5 key-chain if this HSRP group is configured with an MD5 authentication key-chain; otherwise return an empty string.

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_glbp_tracking_interfaces()

Get a list of unique GLBP tracked interfaces. This may never be supported by HSRPInterfaceGroup()

get_hsrp_tracking_interfaces()

Return a list of HSRP TrackingInterface() interfaces for this HSRPInterfaceGroup()

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

get_vrrp_tracking_interfaces()

Get a list of unique VRRP tracked interfaces. This may never be supported by HSRPInterfaceGroup()

property group

Return the integer HSRP Group for this HSRPInterfaceGroup() instance.

grp: int
property has_authentication_md5

Return True if the router is configured with an MD5 key-chain; otherwise return False.

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 has_hsrp_track
property has_ipv6

Return a boolean for whether this interface is configured with an IPv6 HSRP address

property hash_children

Return a unique hash of all children (if the number of children > 0)

property hello_timer

Return the configured integer HSRP hello timer, or the HSRP default of 3 if there is no explicit hello timer.

property hold_timer

Return the configured integer HSRP hold timer, or the HSRP default of 10 if there is no explicit hold timer.

property hsrp_authentication_cleartext
property hsrp_group

Return the integer HSRP group number for this HSRPInterfaceGroup() instance.

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 interface_name

Return the string interface name of the interface owning this HSRP group instance.

property interface_tracking

Return a list of HSRP TrackingInterface() objects for this HSRPInterfaceGroup()

intf_name: str
property ip

Return the string IPv4 HSRP address for this HSRP group

property ipv4

Return the string IPv4 HSRP address for this HSRP group

property ipv6

Return the string IPv6 HSRP address for this HSRP group

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: BaseCfgLine
parent_obj: BaseCfgLine
property preempt

Return True if the router is configured to preempt for this HSRP Group; otherwise return False.

property preempt_delay

Return the configured integer HSRP preempt delay, or 0 if there is none.

property preempt_delay_minimum

Return the configured integer HSRP preempt delay minimum, or 0 if there is none.

property priority

Return the configured integer HSRP priority, or the HSRP default of 100 if there is no explicit HSRP priority configured.

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 use_bia

Return True if the router is configured with standby use-bia; standby use-bia helps avoid instability when introducing new HSRP routers. Return False if the router is not configured with standby use-bia.

property verbose: str
Returns:

A string representation of this object

Return type:

str

property version

Return the configured integer HSRP version, or the HSRP default of 1 if there is no explicit HSRP version configured.

class ciscoconfparse2.models_cisco.IOSCfgLine(*args, **kwargs)

An object for a parsed IOS-style configuration line. IOSCfgLine objects contain references to other parent and child IOSCfgLine objects.

Parameters:
linestr

A string containing a text copy of the IOS configuration line. CiscoConfParse will automatically identify the parent and children (if any) when it parses the configuration.

Returns:
An instance of IOSCfgLine.

Attributes

text

return:

Configuration text

children

Return the direct children of this object

indent

return:

Padding of the number of left spaces of the text property

is_comment

Return True if the line is a comment

linenum

(int) The line number of this configuration statement in the original config; default is -1 when first initialized.

parent

((IOSCfgLine())) The parent of this object; defaults to self.

child_indent

(int) An integer with the indentation of this object’s children

Accept an IOS line number and initialize family relationship attributes

__contains__(arg: str) bool

Implement ‘arg in self’ for this class

__eq__(other) bool

Return self==value.

__gt__(val)

Return self>value.

__hash__() int
Returns:

A unique identifier for this object

Return type:

int

Note

Also see BaseCfgLine.get_unique_identifier().

__iter__() str
__len__() int
__lt__(val)

Return self<value.

__ne__(other) bool

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
classmethod from_list(*list_of_args) BaseCfgLine

Helper-method to allow strictly positional *arg calls .i.e. IOSCfgLine([], ‘hostname Foo’)

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_ethernet_intf: bool
Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is an ethernet interface. Any ethernet interface (10M and up) is considered an ethernet interface.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.is_ethernet_intf
True
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.is_ethernet_intf
False
>>>
property is_in_portchannel: bool
Returns:

Return a boolean indicating whether this port is configured in a port-channel

Return type:

bool

property is_intf: bool

Returns a boolean (True or False) to answer whether this IOSCfgLine is an interface; subinterfaces also return True.

Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is an interface; subinterfaces also return True.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface Serial1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects('^interface\sSerial')[0]
>>> obj.is_intf
True
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.is_intf
True
>>>
property is_loopback_intf: bool
Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is a loopback interface.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface Loopback0',
...     ' ip address 1.1.1.5 255.255.255.255',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects(r'^interface\sFast')[0]
>>> obj.is_loopback_intf
False
>>> obj = parse.find_objects(r'^interface\sLoop')[0]
>>> obj.is_loopback_intf
True
>>>
classmethod is_object_for(all_lines, line, index=None, re=<module 're' from '/usr/lib/python3.11/re/__init__.py'>) bool

Return True if this object should be used for a given configuration line; otherwise return False

classmethod is_object_for_aaa_accounting(line) bool

Return True if this is an object for aaa accounting. Be sure to reject ‘aaa new-model’

classmethod is_object_for_aaa_authentication(line) bool

Return True if this is an object for aaa authentication. Be sure to reject ‘aaa new-model’

classmethod is_object_for_aaa_authorization(line) bool

Return True if this is an object for aaa authorization. Be sure to reject ‘aaa new-model’

classmethod is_object_for_hostname(line) bool
classmethod is_object_for_interface(line) bool

Use this method to determine whether this class should be used for a physical or logical configuration interface class

classmethod is_object_for_ip_route(line) bool
classmethod is_object_for_ipv6_route(line) bool
property is_parent
property is_portchannel_intf: bool
Returns:

Return a boolean indicating whether this port is a port-channel intf

Return type:

bool

property is_subintf: bool
Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is a subinterface.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface Serial1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects(r'^interface\sSerial')[0]
>>> obj.is_subintf
False
>>> obj = parse.find_objects(r'^interface\sATM')[0]
>>> obj.is_subintf
True
>>>
property is_switchport

subclasses will override this method

property is_virtual_intf: bool
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
property portchannel_number: bool
Returns:

Return an integer for the port-channel which it’s configured in, default to -1

Return type:

int

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

class ciscoconfparse2.models_cisco.IOSIntfLine(*args, **kwargs)

Accept an IOS line number and initialize family relationship attributes

Warning

All IOSIntfLine methods are still considered beta-quality, until this notice is removed. The behavior of APIs on this object could change at any time.

__contains__(arg: str) bool

Implement ‘arg in self’ for this class

__eq__(other)

Method generated by attrs for class BaseIOSIntfLine.

__gt__(val)

Return self>value.

__hash__()
Returns:

A unique identifier for this object

Return type:

int

Note

Also see BaseCfgLine.get_unique_identifier().

__iter__() str
__len__() int
__lt__(val)

Return self<value.

__ne__(other)

Method generated by attrs for class BaseIOSIntfLine.

__repr__() str

Return repr(self).

__str__()

Return str(self).

property abbvs: set[str]

A python set of valid abbreviations (lowercased) for the interface

property access_vlan: int
Returns:

An integer access vlan number, default to 1. Return -1 if the port is not a switchport.

Return type:

int

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

property cisco_interface_object: CiscoIOSInterface | CiscoIOSXRInterface

Return a CiscoIOSInterface() instance for this interface

Returns:

The interface name as a CiscoIOSInterface() / CiscoIOSXRInterface() instance, or ‘’ if the object is not an interface. The CiscoIOSInterface instance can be transparently cast as a string into a typical Cisco IOS name.

Return type:

Union[CiscoIOSInterface, CiscoIOSXRInterface]

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
default_ipv4_addr_object: Any
default_ipv6_addr_object: 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 description: str
Returns:

Return the current interface description string, default to ‘’.

Return type:

str

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
classmethod from_list(*list_of_args) BaseCfgLine

Helper-method to allow strictly positional *arg calls .i.e. IOSCfgLine([], ‘hostname Foo’)

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_hsrp_groups() List[HSRPInterfaceGroup]
Returns:

the sequence of configured HSRPInterfaceGroup() instances

Return type:

List[HSRPInterfaceGroup]

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

property has_autonegotiation: bool
Returns:

Whether autonegotiation is enabled on this interface

Return type:

bool

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 has_dtp: bool
Returns:

Whether this interface is configured to use Cisco DTP

Return type:

bool

property has_ip_hsrp: bool
Returns:

Whether this interface has HSRP configured on it

Return type:

bool

property has_ip_pim_dense_mode: bool
Returns:

Whether the interface is configured with IP PIM Dense-Mode

Return type:

bool

property has_ip_pim_sparse_mode: bool
Returns:

Whether the interface is configured with IP PIM Sparse-Mode

Return type:

bool

property has_ip_pim_sparsedense_mode: bool
Returns:

Whether the interface is configured with IP PIM Sparse-Dense-Mode

Return type:

bool

property has_ipv6_pim_sparse_mode: bool
Returns:

Whether the interface is configured with IP PIM Sparse-Mode

Return type:

bool

property has_manual_disable_cdp: bool
Returns:

Whether CDP is manually disabled on this interface

Return type:

bool

property has_manual_switch_access: bool
Returns:

Whether the interface is manually configured as an access switchport

Return type:

bool

property has_manual_switch_trunk: bool
Returns:

Whether this interface is manually configured as a trunk switchport

Return type:

bool

property has_manual_switch_trunk_encap: bool
Returns:

Whether the interface is has a manual switchport trunk encapsulation

Return type:

bool

property has_mpls: bool
Returns:

Whether this interface is configured with MPLS

Return type:

bool

property has_no_icmp_redirects: bool
Returns:

Whether the interface is configured without ICMP redirects

Return type:

bool

property has_no_icmp_unreachables: bool
Returns:

Whether the interface is configured without ICMP unreachables

Return type:

bool

property has_no_ip_proxyarp: bool
Returns:

Whether the interface is configured without Proxy-ARP

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2.ccp_util import IPv4Obj
>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     ' no ip proxy-arp',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.has_no_ip_proxyarp
True
>>>
property has_switch_portsecurity: bool
Returns:

Whether this interface is fully configured with port-security

Return type:

bool

property has_switch_stormcontrol: bool
Returns:

Whether this interface is fully configured with storm-control

Return type:

bool

property has_xconnect: bool
Returns:

Whether this interface has an MPLS or L2TP xconnect

Return type:

bool

property hash_children

Return a unique hash of all children (if the number of children > 0)

property hsrp_authentication_md5_keychain
Returns:

A dict keyed by integer HSRP group number with a string value of the HSRP authentication key-chain name

Return type:

Dict[int,str]

property hsrp_hello_timer
Returns:

A dict keyed by integer HSRP group number with an integer HSRP hello timer

Return type:

Dict[int,float]

property hsrp_hold_timer
Returns:

A dict keyed by integer HSRP group number with an integer HSRP hold timer

Return type:

Dict[int,float]

property hsrp_ip_addr: Dict[int, str]
Returns:

A dict keyed by integer HSRP group number with a string ipv4 address, default to an empty dict

Return type:

Dict[int,str]

property hsrp_ip_addr_secondary: Dict[int, str]
Returns:

A dict keyed by integer HSRP group number with a comma-separated string secondary ipv4 address, default to an empty dict

Return type:

Dict[int,str]

property hsrp_preempt
Returns:

A dict keyed by integer HSRP group number with a bool value for whether the group is configured with preempt

Return type:

Dict[int,bool]

property hsrp_priority: Dict[int, int]
Returns:

A dict keyed by integer HSRP group number with an integer HSRP priority per-group

Return type:

Dict[int,int]

property hsrp_usebia
Returns:

A dict keyed by integer HSRP group number with a bool value for whether the group is configured with use-bia

Return type:

Dict[int,bool]

ifindex: str
in_ipv4_subnet(ipv4network: IPv4Obj = None, strict: bool = False) bool
Returns:

Whether the interface is in a IPv4Obj subnet, default to False.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2.ccp_util import IPv4Obj
>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface Serial1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sSerial')[0]
>>> obj
<IOSIntfLine # 1 'Serial1/0' primary_ipv4: '1.1.1.1/30'>
>>> obj.in_ipv4_subnet(IPv4Obj('1.1.1.0/24', strict=False))
True
>>> obj.in_ipv4_subnet(IPv4Obj('2.1.1.0/24', strict=False))
False
>>>
in_ipv4_subnets(subnets: Set[IPv4Obj] | List[IPv4Obj] | Tuple[IPv4Obj, ...] = None) bool
Returns:

Whether the interface is in a sequence or set of ccp_util.IPv4Obj objects

Return type:

bool

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 interface_number: str
Returns:

Return a string representing the card, slot, port for this interface. If you call interface_number on GigabitEthernet2/25.100, you’ll get this python string: ‘2/25’. If you call interface_number on GigabitEthernet2/0/25.100 you’ll get this python string ‘2/0/25’. This method strips all subinterface information in the returned value.

Return type:

str

Warning

interface_number should silently fail (returning an empty python string) if the interface doesn’t parse correctly

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.interface_number
'1/0'
>>> obj = parse.find_objects('^interface\sATM')[-1]
>>> obj.interface_number
'2/0'
>>>
property ip: IPv4Obj
Returns:

A ccp_util.IPv4Obj object representing the IPv4 address on this interface, default to IPv4Obj()

Return type:

IPv4Obj

property ip_accessgroup_in: str
Returns:

The name or number of the inbound IPv4 access-group

Return type:

str

property ip_accessgroup_out: str
Returns:

The name or number of the outbound IPv4 access-group

Return type:

str

property ip_addr: str
Returns:

The IP address configured on the interface, default to ‘’

Return type:

str

property ip_helper_addresses: List[Dict[str, str]]
Returns:

A sequence of dicts with IP helper-addresses. Each helper-address is in a dictionary.

Return type:

List[Dict[str,str]]

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/1',
...     ' ip address 1.1.1.1 255.255.255.0',
...     ' ip helper-address 172.16.20.12',
...     ' ip helper-address 172.19.185.91',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects('^interface\sFastEthernet1/1$')[0]
>>> obj.ip_helper_addresses
[{'addr': '172.16.20.12', 'vrf': '', 'scope': 'local'}, {'addr': '172.19.185.91', 'vrf': '', 'scope': 'local'}]
>>>
property ip_network_object: IPv4Obj
Returns:

A ccp_util.IPv4Obj object representing the IPv4 subnet on this interface, default to IPv4Obj()

Return type:

IPv4Obj

property ip_secondary_addresses: set[str]
Returns:

Return a set of IPv4 secondary addresses (as strings), default to an empty set

Return type:

set[str]

property ip_secondary_networks: set[str]
Returns:

Return a set of IPv4 network / prefixlen (as strings), default to an empty set

Return type:

set[str]

property ipv4: IPv4Obj
Returns:

A ccp_util.IPv4Obj object representing the IPv4 address on this interface, default to IPv4Obj()

Return type:

IPv4Obj

property ipv4_accessgroup_in: str
Returns:

The name or number of the inbound IPv4 access-group

Return type:

str

property ipv4_accessgroup_out: str
Returns:

The name or number of the outbound IPv4 access-group

Return type:

str

property ipv4_addr: str
Returns:

The IP address configured on the interface, default to ‘’

Return type:

str

property ipv4_addr_object: IPv4Obj
Returns:

A ccp_util.IPv4Obj object representing the address on this interface, default to IPv4Obj()

Return type:

IPv4Obj

property ipv4_masklength: int
Returns:

Return an integer with the interface’s IPv4 mask length, default to -1

Return type:

int

property ipv4_netmask: str
Returns:

The IP netmask configured on the interface, default to ‘’

Return type:

str

property ipv4_network_object: IPv4Obj
Returns:

A ccp_util.IPv4Obj object representing the IPv4 subnet on this interface, default to IPv4Obj()

Return type:

IPv4Obj

property ipv6_accessgroup_in: str

Alias for ipv6_trafficfilter_in

Returns:

The name or number of the inbound IPv6 ACL

Return type:

str

property ipv6_accessgroup_out: str

Alias for ipv6_trafficfilter_out

Returns:

The name or number of the outbound IPv6 ACL

Return type:

str

property ipv6_addr: str
Returns:

The IPv6 address configured on the interface, default to ‘’

Return type:

str

property ipv6_addr_objects: Dict[str, List[IPv6Obj]]
Returns:

A Dict of ccp_util.IPv6Obj objects representing the addresss on this interface, default to {}

Return type:

IPv6Obj

property ipv6_dhcp_server: List[Dict[str, str]]
Returns:

A sequence of dicts with IPv6 dhcp server. Each address is in a dictionary.

Return type:

List[Dict[str,str]]

property ipv6_masklength: int
Returns:

The IPv6 masklength configured on the interface, default to -1

Return type:

int

property ipv6_trafficfilter_in: str
Returns:

The name or number of the inbound IPv6 ACL

Return type:

str

property ipv6_trafficfilter_out: str
Returns:

The name or number of the outbound IPv6 ACL

Return type:

str

is_abbreviated_as(value: str) int
Returns:

Whether value is a good abbreviation for the interface

Return type:

bool

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_ethernet_intf: bool
Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is an ethernet interface. Any ethernet interface (10M and up) is considered an ethernet interface.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.is_ethernet_intf
True
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.is_ethernet_intf
False
>>>
property is_in_portchannel: bool
Returns:

Return a boolean indicating whether this port is configured in a port-channel

Return type:

bool

property is_intf: bool

Returns a boolean (True or False) to answer whether this IOSCfgLine is an interface; subinterfaces also return True.

Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is an interface; subinterfaces also return True.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface Serial1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects('^interface\sSerial')[0]
>>> obj.is_intf
True
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.is_intf
True
>>>
property is_loopback_intf: bool
Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is a loopback interface.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface Loopback0',
...     ' ip address 1.1.1.5 255.255.255.255',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects(r'^interface\sFast')[0]
>>> obj.is_loopback_intf
False
>>> obj = parse.find_objects(r'^interface\sLoop')[0]
>>> obj.is_loopback_intf
True
>>>
classmethod is_object_for(all_lines, line, index=None, re=<module 're' from '/usr/lib/python3.11/re/__init__.py'>)

Return True if this object should be used for a given configuration line; otherwise return False

classmethod is_object_for_aaa_accounting(line) bool

Return True if this is an object for aaa accounting. Be sure to reject ‘aaa new-model’

classmethod is_object_for_aaa_authentication(line) bool

Return True if this is an object for aaa authentication. Be sure to reject ‘aaa new-model’

classmethod is_object_for_aaa_authorization(line) bool

Return True if this is an object for aaa authorization. Be sure to reject ‘aaa new-model’

classmethod is_object_for_hostname(line) bool
classmethod is_object_for_interface(line) bool

Use this method to determine whether this class should be used for a physical or logical configuration interface class

classmethod is_object_for_ip_route(line) bool
classmethod is_object_for_ipv6_route(line) bool
property is_parent
property is_portchannel_intf: bool
Returns:

Return a boolean indicating whether this port is a port-channel intf

Return type:

bool

property is_shutdown: bool
Returns:

Whether the interface is shutdown

Return type:

bool

property is_subintf: bool
Returns:

Returns a boolean (True or False) to answer whether this ciscoconfparse2.models_base.BaseFactoryLine is a subinterface.

Return type:

bool

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface Serial1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config)
>>> obj = parse.find_objects(r'^interface\sSerial')[0]
>>> obj.is_subintf
False
>>> obj = parse.find_objects(r'^interface\sATM')[0]
>>> obj.is_subintf
True
>>>
property is_switchport: bool
Returns:

Whether the interface is a switchport

Return type:

bool

property is_virtual_intf: bool
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

property mac_accessgroup_in: bool
Returns:

Whether this interface has an inbound mac access-list

Return type:

bool

property mac_accessgroup_out: bool
Returns:

Whether this interface has an outbound mac access-list

Return type:

bool

property manual_arp_timeout: int
Returns:

An integer with the manual ARP timeout, default to -1

Return type:

int

property manual_bandwidth: int
Returns:

Return the integer bandwidth, default to -1

Return type:

int

property manual_carrierdelay: float
Returns:

The manual carrier delay (in seconds) of the interface as a python float, default to -1.0

Return type:

float

property manual_clock_rate: int
Returns:

Return the clock rate of the interface as a python integer, default to -1

Return type:

int

property manual_delay: int
Returns:

Return the integer delay

Return type:

int

property manual_duplex: str
Returns:

Return the manual duplex of the interface as a python integer, default to ‘’

Return type:

str

property manual_encapsulation: str
Returns:

Return the current encapsulation (i.e. ppp, hdlc, ethernet, etc…), default to ‘’

Return type:

str

property manual_holdqueue_in: int
Returns:

Return the current hold-queue int depth, default to -1

Return type:

int

property manual_holdqueue_out: int
Returns:

Return the current hold-queue out depth, default to -1

Return type:

int

property manual_ip_mtu: int
Returns:

Return the manual IP MTU of the interface as a python integer, default to -1

Return type:

int

property manual_ipv6_mtu: int
Returns:

Return the manual IPv6 MTU of the interface as a python integer, default to -1

Return type:

int

property manual_mpls_mtu: int
Returns:

Return the manual MPLS MTU of the interface as a python integer, default to -1

Return type:

int

property manual_mtu: int
Returns:

Return the manual MTU of the interface as a python integer, default to -1

Return type:

int

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' mtu 4470',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.manual_mtu
-1
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.manual_mtu
4470
>>>
property manual_speed: int
Returns:

Return the manual speed of the interface as a python integer, default to -1

Return type:

int

property manual_switch_trunk_encap: str
Returns:

The type of trunk encapsulation of this switchport.

Return type:

str

property name: str
Returns:

The interface name as a string, such as ‘GigabitEthernet0/1’

Return type:

str

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.name
'FastEthernet1/0'
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.name
'ATM2/0'
>>> obj = parse.find_objects('^interface\sATM')[1]
>>> obj.name
'ATM2/0.100'
>>>
property native_vlan: int
Returns:

Return an integer with the native vlan number. Return 1, if the switchport has no explicit native vlan configured; return -1 if the port isn’t a switchport

Return type:

int

property ordinal_list: tuple[int, ...]
Returns:

Return a tuple of integers representing card, slot, port for this interface. If you call ordinal_list on GigabitEthernet2/25.100, you’ll get this python tuple of integers: (2, 25). If you call ordinal_list on GigabitEthernet2/0/25.100 you’ll get this python list of integers: (2, 0, 25). This method strips all subinterface information in the returned value.

Return type:

tuple[int, …]

Warning

ordinal_list should silently fail (returning an empty python tuple) if the interface doesn’t parse correctly

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.ordinal_list
(1, 0)
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.ordinal_list
(2, 0)
>>>
parent: Any
property port: int
Returns:

The interface’s port number

Return type:

int

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.port
0
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.port
0
>>>
property port_type: str
Returns:

The port type: Loopback, ATM, GigabitEthernet, Virtual-Template, etc…

Return type:

str

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.port_type
'FastEthernet'
>>> obj = parse.find_objects('^interface\sATM')[0]
>>> obj.port_type
'ATM'
>>>
property portchannel_number: bool
Returns:

Return an integer for the port-channel which it’s configured in, default to -1

Return type:

int

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 subinterface_number: str
Returns:

Return a string representing the card, slot, port for this interface or subinterface. If you call subinterface_number on GigabitEthernet2/25.100, you’ll get this python string: ‘2/25.100’. If you call interface_number on GigabitEthernet2/0/25 you’ll get this python string ‘2/0/25’. This method strips all subinterface information in the returned value.

Return type:

str

Warning

subinterface_number should silently fail (returning an empty python string) if the interface doesn’t parse correctly

This example illustrates use of the method.

>>> from ciscoconfparse2 import CiscoConfParse
>>> config = [
...     '!',
...     'interface FastEthernet1/0',
...     ' ip address 1.1.1.1 255.255.255.252',
...     '!',
...     'interface ATM2/0',
...     ' no ip address',
...     '!',
...     'interface ATM2/0.100 point-to-point',
...     ' ip address 1.1.1.5 255.255.255.252',
...     ' pvc 0/100',
...     '  vbr-nrt 704 704',
...     '!',
...     ]
>>> parse = CiscoConfParse(config, factory=True)
>>> obj = parse.find_objects('^interface\sFast')[0]
>>> obj.subinterface_number
'1/0'
>>> obj = parse.find_objects('^interface\sATM')[-1]
>>> obj.subinterface_number
'2/0.100'
>>>
property text: str
Returns:

Configuration text

Return type:

str

property trunk_vlans_allowed: CiscoRange
Returns:

A CiscoRange() with the list of allowed vlan numbers (as int).

Return type:

CiscoRange

property verbose: str
Returns:

A string representation of this object

Return type:

str

property vrf: str
Returns:

The name of the VRF configured on the interface, default to ‘’

Return type:

str

property xconnect_vc: int
Returns:

The virtual circuit ID of the xconnect on this interface, default to -1 (even if no xconnect)

Return type:

int