_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q19800
|
Ospf.set_router_id
|
train
|
def set_router_id(self, value=None, default=False, disable=False):
"""Controls the router id property for the OSPF Proccess
Args:
value (str): The router-id value
default (bool): Controls the use of the default keyword
disable (bool): Controls the use of the no keyword
Returns:
bool: True if the commands are completed successfully
"""
cmd = self.command_builder('router-id', value=value,
default=default, disable=disable)
return self.configure_ospf(cmd)
|
python
|
{
"resource": ""
}
|
q19801
|
Ospf.add_network
|
train
|
def add_network(self, network, netmask, area=0):
"""Adds a network to be advertised by OSPF
Args:
network (str): The network to be advertised in dotted decimal
notation
netmask (str): The netmask to configure
area (str): The area the network belongs to.
By default this value is 0
Returns:
bool: True if the command completes successfully
Exception:
ValueError: This will get raised if network or netmask
are not passed to the method
"""
if network == '' or netmask == '':
raise ValueError('network and mask values '
'may not be empty')
cmd = 'network {}/{} area {}'.format(network, netmask, area)
return self.configure_ospf(cmd)
|
python
|
{
"resource": ""
}
|
q19802
|
Ospf.add_redistribution
|
train
|
def add_redistribution(self, protocol, route_map_name=None):
"""Adds a protocol redistribution to OSPF
Args:
protocol (str): protocol to redistribute
route_map_name (str): route-map to be used to
filter the protocols
Returns:
bool: True if the command completes successfully
Exception:
ValueError: This will be raised if the protocol pass is not one
of the following: [rip, bgp, static, connected]
"""
protocols = ['bgp', 'rip', 'static', 'connected']
if protocol not in protocols:
raise ValueError('redistributed protocol must be'
'bgp, connected, rip or static')
if route_map_name is None:
cmd = 'redistribute {}'.format(protocol)
else:
cmd = 'redistribute {} route-map {}'.format(protocol,
route_map_name)
return self.configure_ospf(cmd)
|
python
|
{
"resource": ""
}
|
q19803
|
Ospf.remove_redistribution
|
train
|
def remove_redistribution(self, protocol):
"""Removes a protocol redistribution to OSPF
Args:
protocol (str): protocol to redistribute
route_map_name (str): route-map to be used to
filter the protocols
Returns:
bool: True if the command completes successfully
Exception:
ValueError: This will be raised if the protocol pass is not one
of the following: [rip, bgp, static, connected]
"""
protocols = ['bgp', 'rip', 'static', 'connected']
if protocol not in protocols:
raise ValueError('redistributed protocol must be'
'bgp, connected, rip or static')
cmd = 'no redistribute {}'.format(protocol)
return self.configure_ospf(cmd)
|
python
|
{
"resource": ""
}
|
q19804
|
StaticRoute.getall
|
train
|
def getall(self):
"""Return all ip routes configured on the switch as a resource dict
Returns:
dict: An dict object of static route entries in the form::
{ ip_dest:
{ next_hop:
{ next_hop_ip:
{ distance:
{ 'tag': tag,
'route_name': route_name
}
}
}
}
}
If the ip address specified does not have any associated
static routes, then None is returned.
Notes:
The keys ip_dest, next_hop, next_hop_ip, and distance in
the returned dictionary are the values of those components
of the ip route specification. If a route does not contain
a next_hop_ip, then that key value will be set as 'None'.
"""
# Find all the ip routes in the config
matches = ROUTES_RE.findall(self.config)
# Parse the routes and add them to the routes dict
routes = dict()
for match in matches:
# Get the four identifying components
ip_dest = match[0]
next_hop = match[1]
next_hop_ip = None if match[2] is '' else match[2]
distance = int(match[3])
# Create the data dict with the remaining components
data = {}
data['tag'] = None if match[4] is '' else int(match[4])
data['route_name'] = None if match[5] is '' else match[5]
# Build the complete dict entry from the four components
# and the data.
# temp_dict = parent_dict[key] = parent_dict.get(key, {})
# This creates the keyed dict in the parent_dict if it doesn't
# exist, or reuses the existing keyed dict.
# The temp_dict is used to make things more readable.
ip_dict = routes[ip_dest] = routes.get(ip_dest, {})
nh_dict = ip_dict[next_hop] = ip_dict.get(next_hop, {})
nhip_dict = nh_dict[next_hop_ip] = nh_dict.get(next_hop_ip, {})
nhip_dict[distance] = data
return routes
|
python
|
{
"resource": ""
}
|
q19805
|
StaticRoute.create
|
train
|
def create(self, ip_dest, next_hop, **kwargs):
"""Create a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name
Returns:
True if the operation succeeds, otherwise False.
"""
# Call _set_route with delete and default set to False
return self._set_route(ip_dest, next_hop, **kwargs)
|
python
|
{
"resource": ""
}
|
q19806
|
StaticRoute.delete
|
train
|
def delete(self, ip_dest, next_hop, **kwargs):
"""Delete a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name
Returns:
True if the operation succeeds, otherwise False.
"""
# Call _set_route with the delete flag set to True
kwargs.update({'delete': True})
return self._set_route(ip_dest, next_hop, **kwargs)
|
python
|
{
"resource": ""
}
|
q19807
|
StaticRoute.set_tag
|
train
|
def set_tag(self, ip_dest, next_hop, **kwargs):
"""Set the tag value for the specified route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name
Returns:
True if the operation succeeds, otherwise False.
Notes:
Any existing route_name value must be included in call to
set_tag, otherwise the tag will be reset
by the call to EOS.
"""
# Call _set_route with the new tag information
return self._set_route(ip_dest, next_hop, **kwargs)
|
python
|
{
"resource": ""
}
|
q19808
|
StaticRoute.set_route_name
|
train
|
def set_route_name(self, ip_dest, next_hop, **kwargs):
"""Set the route_name value for the specified route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name
Returns:
True if the operation succeeds, otherwise False.
Notes:
Any existing tag value must be included in call to
set_route_name, otherwise the tag will be reset
by the call to EOS.
"""
# Call _set_route with the new route_name information
return self._set_route(ip_dest, next_hop, **kwargs)
|
python
|
{
"resource": ""
}
|
q19809
|
StaticRoute._build_commands
|
train
|
def _build_commands(self, ip_dest, next_hop, **kwargs):
"""Build the EOS command string for ip route interactions.
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name
Returns the ip route command string to be sent to the switch for
the given set of parameters.
"""
commands = "ip route %s %s" % (ip_dest, next_hop)
next_hop_ip = kwargs.get('next_hop_ip', None)
distance = kwargs.get('distance', None)
tag = kwargs.get('tag', None)
route_name = kwargs.get('route_name', None)
if next_hop_ip is not None:
commands += " %s" % next_hop_ip
if distance is not None:
commands += " %s" % distance
if tag is not None:
commands += " tag %s" % tag
if route_name is not None:
commands += " name %s" % route_name
return commands
|
python
|
{
"resource": ""
}
|
q19810
|
StaticRoute._set_route
|
train
|
def _set_route(self, ip_dest, next_hop, **kwargs):
"""Configure a static route
Args:
ip_dest (string): The ip address of the destination in the
form of A.B.C.D/E
next_hop (string): The next hop interface or ip address
**kwargs['next_hop_ip'] (string): The next hop address on
destination interface
**kwargs['distance'] (string): Administrative distance for this
route
**kwargs['tag'] (string): Route tag
**kwargs['route_name'] (string): Route name
**kwargs['delete'] (boolean): If true, deletes the specified route
instead of creating or setting values for the route
**kwargs['default'] (boolean): If true, defaults the specified
route instead of creating or setting values for the route
Returns:
True if the operation succeeds, otherwise False.
"""
commands = self._build_commands(ip_dest, next_hop, **kwargs)
delete = kwargs.get('delete', False)
default = kwargs.get('default', False)
# Prefix with 'no' if delete is set
if delete:
commands = "no " + commands
# Or with 'default' if default is setting
else:
if default:
commands = "default " + commands
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19811
|
Vlans.get
|
train
|
def get(self, value):
"""Returns the VLAN configuration as a resource dict.
Args:
vid (string): The vlan identifier to retrieve from the
running configuration. Valid values are in the range
of 1 to 4095
Returns:
A Python dict object containing the VLAN attributes as
key/value pairs.
"""
config = self.get_block('vlan %s' % value)
if not config:
return None
response = dict(vlan_id=value)
response.update(self._parse_name(config))
response.update(self._parse_state(config))
response.update(self._parse_trunk_groups(config))
return response
|
python
|
{
"resource": ""
}
|
q19812
|
Vlans._parse_name
|
train
|
def _parse_name(self, config):
""" _parse_name scans the provided configuration block and extracts
the vlan name. The config block is expected to always return the
vlan name. The return dict is intended to be merged into the response
dict.
Args:
config (str): The vlan configuration block from the nodes running
configuration
Returns:
dict: resource dict attribute
"""
value = NAME_RE.search(config).group('value')
return dict(name=value)
|
python
|
{
"resource": ""
}
|
q19813
|
Vlans._parse_state
|
train
|
def _parse_state(self, config):
""" _parse_state scans the provided configuration block and extracts
the vlan state value. The config block is expected to always return
the vlan state config. The return dict is inteded to be merged into
the response dict.
Args:
config (str): The vlan configuration block from the nodes
running configuration
Returns:
dict: resource dict attribute
"""
value = STATE_RE.search(config).group('value')
return dict(state=value)
|
python
|
{
"resource": ""
}
|
q19814
|
Vlans._parse_trunk_groups
|
train
|
def _parse_trunk_groups(self, config):
""" _parse_trunk_groups scans the provided configuration block and
extracts all the vlan trunk groups. If no trunk groups are configured
an empty List is returned as the vlaue. The return dict is intended
to be merged into the response dict.
Args:
config (str): The vlan configuration block form the node's
running configuration
Returns:
dict: resource dict attribute
"""
values = TRUNK_GROUP_RE.findall(config)
return dict(trunk_groups=values)
|
python
|
{
"resource": ""
}
|
q19815
|
Vlans.getall
|
train
|
def getall(self):
"""Returns a dict object of all Vlans in the running-config
Returns:
A dict object of Vlan attributes
"""
vlans_re = re.compile(r'(?<=^vlan\s)(\d+)', re.M)
response = dict()
for vid in vlans_re.findall(self.config):
response[vid] = self.get(vid)
return response
|
python
|
{
"resource": ""
}
|
q19816
|
Vlans.create
|
train
|
def create(self, vid):
""" Creates a new VLAN resource
Args:
vid (str): The VLAN ID to create
Returns:
True if create was successful otherwise False
"""
command = 'vlan %s' % vid
return self.configure(command) if isvlan(vid) else False
|
python
|
{
"resource": ""
}
|
q19817
|
Vlans.delete
|
train
|
def delete(self, vid):
""" Deletes a VLAN from the running configuration
Args:
vid (str): The VLAN ID to delete
Returns:
True if the operation was successful otherwise False
"""
command = 'no vlan %s' % vid
return self.configure(command) if isvlan(vid) else False
|
python
|
{
"resource": ""
}
|
q19818
|
Vlans.default
|
train
|
def default(self, vid):
""" Defaults the VLAN configuration
.. code-block:: none
default vlan <vlanid>
Args:
vid (str): The VLAN ID to default
Returns:
True if the operation was successful otherwise False
"""
command = 'default vlan %s' % vid
return self.configure(command) if isvlan(vid) else False
|
python
|
{
"resource": ""
}
|
q19819
|
Vlans.configure_vlan
|
train
|
def configure_vlan(self, vid, commands):
""" Configures the specified Vlan using commands
Args:
vid (str): The VLAN ID to configure
commands: The list of commands to configure
Returns:
True if the commands completed successfully
"""
commands = make_iterable(commands)
commands.insert(0, 'vlan %s' % vid)
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19820
|
Vlans.set_name
|
train
|
def set_name(self, vid, name=None, default=False, disable=False):
""" Configures the VLAN name
EosVersion:
4.13.7M
Args:
vid (str): The VLAN ID to Configures
name (str): The value to configure the vlan name
default (bool): Defaults the VLAN ID name
disable (bool): Negates the VLAN ID name
Returns:
True if the operation was successful otherwise False
"""
cmds = self.command_builder('name', value=name, default=default,
disable=disable)
return self.configure_vlan(vid, cmds)
|
python
|
{
"resource": ""
}
|
q19821
|
Vlans.set_state
|
train
|
def set_state(self, vid, value=None, default=False, disable=False):
""" Configures the VLAN state
EosVersion:
4.13.7M
Args:
vid (str): The VLAN ID to configure
value (str): The value to set the vlan state to
default (bool): Configures the vlan state to its default value
disable (bool): Negates the vlan state
Returns:
True if the operation was successful otherwise False
"""
cmds = self.command_builder('state', value=value, default=default,
disable=disable)
return self.configure_vlan(vid, cmds)
|
python
|
{
"resource": ""
}
|
q19822
|
Vlans.set_trunk_groups
|
train
|
def set_trunk_groups(self, vid, value=None, default=False, disable=False):
""" Configures the list of trunk groups support on a vlan
This method handles configuring the vlan trunk group value to default
if the default flag is set to True. If the default flag is set
to False, then this method will calculate the set of trunk
group names to be added and to be removed.
EosVersion:
4.13.7M
Args:
vid (str): The VLAN ID to configure
value (str): The list of trunk groups that should be configured
for this vlan id.
default (bool): Configures the trunk group value to default if
this value is true
disable (bool): Negates the trunk group value if set to true
Returns:
True if the operation was successful otherwise False
"""
if default:
return self.configure_vlan(vid, 'default trunk group')
if disable:
return self.configure_vlan(vid, 'no trunk group')
current_value = self.get(vid)['trunk_groups']
failure = False
value = make_iterable(value)
for name in set(value).difference(current_value):
if not self.add_trunk_group(vid, name):
failure = True
for name in set(current_value).difference(value):
if not self.remove_trunk_group(vid, name):
failure = True
return not failure
|
python
|
{
"resource": ""
}
|
q19823
|
EapiConnection.authentication
|
train
|
def authentication(self, username, password):
"""Configures the user authentication for eAPI
This method configures the username and password combination to use
for authenticating to eAPI.
Args:
username (str): The username to use to authenticate the eAPI
connection with
password (str): The password in clear text to use to authenticate
the eAPI connection with
"""
_auth_text = '{}:{}'.format(username, password)
# Work around for Python 2.7/3.x compatibility
if int(sys.version[0]) > 2:
# For Python 3.x
_auth_bin = base64.encodebytes(_auth_text.encode())
_auth = _auth_bin.decode()
_auth = _auth.replace('\n', '')
self._auth = _auth
else:
# For Python 2.7
_auth = base64.encodestring(_auth_text)
self._auth = str(_auth).replace('\n', '')
_LOGGER.debug('Autentication string is: {}:***'.format(username))
|
python
|
{
"resource": ""
}
|
q19824
|
EapiConnection.request
|
train
|
def request(self, commands, encoding=None, reqid=None, **kwargs):
"""Generates an eAPI request object
This method will take a list of EOS commands and generate a valid
eAPI request object form them. The eAPI request object is then
JSON encoding and returned to the caller.
eAPI Request Object
.. code-block:: json
{
"jsonrpc": "2.0",
"method": "runCmds",
"params": {
"version": 1,
"cmds": [
<commands>
],
"format": [json, text],
}
"id": <reqid>
}
Args:
commands (list): A list of commands to include in the eAPI
request object
encoding (string): The encoding method passed as the `format`
parameter in the eAPI request
reqid (string): A custom value to assign to the request ID
field. This value is automatically generated if not passed
**kwargs: Additional keyword arguments for expanded eAPI
functionality. Only supported eAPI params are used in building
the request
Returns:
A JSON encoding request structure that can be send over eAPI
"""
commands = make_iterable(commands)
reqid = id(self) if reqid is None else reqid
params = {'version': 1, 'cmds': commands, 'format': encoding}
if 'autoComplete' in kwargs:
params['autoComplete'] = kwargs['autoComplete']
if 'expandAliases' in kwargs:
params['expandAliases'] = kwargs['expandAliases']
return json.dumps({'jsonrpc': '2.0', 'method': 'runCmds',
'params': params, 'id': str(reqid)})
|
python
|
{
"resource": ""
}
|
q19825
|
EapiConnection.send
|
train
|
def send(self, data):
"""Sends the eAPI request to the destination node
This method is responsible for sending an eAPI request to the
destination node and returning a response based on the eAPI response
object. eAPI responds to request messages with either a success
message or failure message.
eAPI Response - success
.. code-block:: json
{
"jsonrpc": "2.0",
"result": [
{},
{}
{
"warnings": [
<message>
]
},
],
"id": <reqid>
}
eAPI Response - failure
.. code-block:: json
{
"jsonrpc": "2.0",
"error": {
"code": <int>,
"message": <string>
"data": [
{},
{},
{
"errors": [
<message>
]
}
]
}
"id": <reqid>
}
Args:
data (string): The data to be included in the body of the eAPI
request object
Returns:
A decoded response. The response object is deserialized from
JSON and returned as a standard Python dictionary object
Raises:
CommandError if an eAPI failure response object is returned from
the node. The CommandError exception includes the error
code and error message from the eAPI response.
"""
try:
_LOGGER.debug('Request content: {}'.format(data))
# debug('eapi_request: %s' % data)
self.transport.putrequest('POST', '/command-api')
self.transport.putheader('Content-type', 'application/json-rpc')
self.transport.putheader('Content-length', '%d' % len(data))
if self._auth:
self.transport.putheader('Authorization',
'Basic %s' % self._auth)
if int(sys.version[0]) > 2:
# For Python 3.x compatibility
data = data.encode()
self.transport.endheaders(message_body=data)
try: # Python 2.7: use buffering of HTTP responses
response = self.transport.getresponse(buffering=True)
except TypeError: # Python 2.6: older, and 3.x on
response = self.transport.getresponse()
response_content = response.read()
_LOGGER.debug('Response: status:{status}, reason:{reason}'.format(
status=response.status,
reason=response.reason))
_LOGGER.debug('Response content: {}'.format(response_content))
if response.status == 401:
raise ConnectionError(str(self), '%s. %s' % (response.reason,
response_content))
# Work around for Python 2.7/3.x compatibility
if not type(response_content) == str:
# For Python 3.x - decode bytes into string
response_content = response_content.decode()
decoded = json.loads(response_content)
_LOGGER.debug('eapi_response: %s' % decoded)
if 'error' in decoded:
(code, msg, err, out) = self._parse_error_message(decoded)
pattern = "unexpected keyword argument '(.*)'"
match = re.search(pattern, msg)
if match:
auto_msg = ('%s parameter is not supported in this'
' version of EOS.' % match.group(1))
_LOGGER.error(auto_msg)
msg = msg + '. ' + auto_msg
raise CommandError(code, msg, command_error=err, output=out)
return decoded
# socket.error is deprecated in python 3 and replaced with OSError.
except (socket.error, OSError) as exc:
_LOGGER.exception(exc)
self.socket_error = exc
self.error = exc
error_msg = 'Socket error during eAPI connection: %s' % str(exc)
raise ConnectionError(str(self), error_msg)
except ValueError as exc:
_LOGGER.exception(exc)
self.socket_error = None
self.error = exc
raise ConnectionError(str(self), 'unable to connect to eAPI')
finally:
self.transport.close()
|
python
|
{
"resource": ""
}
|
q19826
|
EapiConnection._parse_error_message
|
train
|
def _parse_error_message(self, message):
"""Parses the eAPI failure response message
This method accepts an eAPI failure message and parses the necesary
parts in order to generate a CommandError.
Args:
message (str): The error message to parse
Returns:
tuple: A tuple that consists of the following:
* code: The error code specified in the failure message
* message: The error text specified in the failure message
* error: The error text from the command that generated the
error (the last command that ran)
* output: A list of all output from all commands
"""
msg = message['error']['message']
code = message['error']['code']
err = None
out = None
if 'data' in message['error']:
err = ' '.join(message['error']['data'][-1]['errors'])
out = message['error']['data']
return code, msg, err, out
|
python
|
{
"resource": ""
}
|
q19827
|
EapiConnection.execute
|
train
|
def execute(self, commands, encoding='json', **kwargs):
"""Executes the list of commands on the destination node
This method takes a list of commands and sends them to the
destination node, returning the results. The execute method handles
putting the destination node in enable mode and will pass the
enable password, if required.
Args:
commands (list): A list of commands to execute on the remote node
encoding (string): The encoding to send along with the request
message to the destination node. Valid values include 'json'
or 'text'. This argument will influence the response object
encoding
**kwargs: Arbitrary keyword arguments
Returns:
A decoded response message as a native Python dictionary object
that has been deserialized from JSON.
Raises:
CommandError: A CommandError is raised that includes the error
code, error message along with the list of commands that were
sent to the node. The exception instance is also stored in
the error property and is availble until the next request is
sent
"""
if encoding not in ('json', 'text'):
raise TypeError('encoding must be one of [json, text]')
try:
self.error = None
request = self.request(commands, encoding=encoding, **kwargs)
response = self.send(request)
return response
except(ConnectionError, CommandError, TypeError) as exc:
exc.commands = commands
self.error = exc
raise
|
python
|
{
"resource": ""
}
|
q19828
|
Varp.get
|
train
|
def get(self):
"""Returns the current VARP configuration
The Varp resource returns the following:
* mac_address (str): The virtual-router mac address
* interfaces (dict): A list of the interfaces that have a
virtual-router address configured.
Return:
A Python dictionary object of key/value pairs that represents
the current configuration of the node. If the specified
interface does not exist then None is returned::
{
"mac_address": "aa:bb:cc:dd:ee:ff",
"interfaces": {
"Vlan100": {
"addresses": [ "1.1.1.1", "2.2.2.2"]
},
"Vlan200": [...]
}
}
"""
resource = dict()
resource.update(self._parse_mac_address())
resource.update(self._parse_interfaces())
return resource
|
python
|
{
"resource": ""
}
|
q19829
|
Varp.set_mac_address
|
train
|
def set_mac_address(self, mac_address=None, default=False, disable=False):
""" Sets the virtual-router mac address
This method will set the switch virtual-router mac address. If a
virtual-router mac address already exists it will be overwritten.
Args:
mac_address (string): The mac address that will be assigned as
the virtual-router mac address. This should be in the format,
aa:bb:cc:dd:ee:ff.
default (bool): Sets the virtual-router mac address to the system
default (which is to remove the configuration line).
disable (bool): Negates the virtual-router mac address using
the system no configuration command
Returns:
True if the set operation succeeds otherwise False.
"""
base_command = 'ip virtual-router mac-address'
if not default and not disable:
if mac_address is not None:
# Check to see if mac_address matches expected format
if not re.match(r'(?:[a-f0-9]{2}:){5}[a-f0-9]{2}',
mac_address):
raise ValueError('mac_address must be formatted like:'
'aa:bb:cc:dd:ee:ff')
else:
raise ValueError('mac_address must be a properly formatted '
'address string')
if default or disable and not mac_address:
current_mac = self._parse_mac_address()
if current_mac['mac_address']:
base_command = base_command + ' ' + current_mac['mac_address']
commands = self.command_builder(base_command, value=mac_address,
default=default, disable=disable)
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19830
|
BaseEntity.get_block
|
train
|
def get_block(self, parent, config='running_config'):
""" Scans the config and returns a block of code
Args:
parent (str): The parent string to search the config for and
return the block
config (str): A text config string to be searched. Default
is to search the running-config of the Node.
Returns:
A string object that represents the block from the config. If
the parent string is not found, then this method will
return None.
"""
try:
parent = r'^%s$' % parent
return self.node.section(parent, config=config)
except TypeError:
return None
|
python
|
{
"resource": ""
}
|
q19831
|
BaseEntity.configure
|
train
|
def configure(self, commands):
"""Sends the commands list to the node in config mode
This method performs configuration the node using the array of
commands specified. This method wraps the configuration commands
in a try/except block and stores any exceptions in the error
property.
Note:
If the return from this method is False, use the error property
to investigate the exception
Args:
commands (list): A list of commands to be sent to the node in
config mode
Returns:
True if the commands are executed without exception otherwise
False is returned
"""
try:
self.node.config(commands)
return True
except (CommandError, ConnectionError):
return False
|
python
|
{
"resource": ""
}
|
q19832
|
BaseEntity.command_builder
|
train
|
def command_builder(self, string, value=None, default=None, disable=None):
"""Builds a command with keywords
Notes:
Negating a command string by overriding 'value' with None or an
assigned value that evalutates to false has been deprecated.
Please use 'disable' to negate a command.
Parameters are evaluated in the order 'default', 'disable', 'value'
Args:
string (str): The command string
value (str): The configuration setting to subsititue into the
command string. If value is a boolean and True, just the
command string is used
default (bool): Specifies the command should use the default
keyword argument. Default preempts disable and value.
disable (bool): Specifies the command should use the no
keyword argument. Disable preempts value.
Returns:
A command string that can be used to configure the node
"""
if default:
return 'default %s' % string
elif disable:
return 'no %s' % string
elif value is True:
return string
elif value:
return '%s %s' % (string, value)
else:
return 'no %s' % string
|
python
|
{
"resource": ""
}
|
q19833
|
BaseEntity.configure_interface
|
train
|
def configure_interface(self, name, commands):
"""Configures the specified interface with the commands
Args:
name (str): The interface name to configure
commands: The commands to configure in the interface
Returns:
True if the commands completed successfully
"""
commands = make_iterable(commands)
commands.insert(0, 'interface %s' % name)
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19834
|
Ntp.get
|
train
|
def get(self):
"""Returns the current NTP configuration
The Ntp resource returns the following:
* source_interface (str): The interface port that specifies
NTP server
* servers (list): A list of the NTP servers that have been
assigned to the node. Each entry in the
list is a key/value pair of the name of
the server as the key and None or 'prefer'
as the value if the server is preferred.
Returns:
A Python dictionary object of key/value pairs that represents
the current NTP configuration of the node::
{
"source_interface": 'Loopback0',
'servers': [
{ '1.1.1.1': None },
{ '1.1.1.2': 'prefer' },
{ '1.1.1.3': 'prefer' },
{ '1.1.1.4': None },
]
}
"""
config = self.config
if not config:
return None
response = dict()
response.update(self._parse_source_interface(config))
response.update(self._parse_servers(config))
return response
|
python
|
{
"resource": ""
}
|
q19835
|
Ntp.delete
|
train
|
def delete(self):
"""Delete the NTP source entry from the node.
Returns:
True if the operation succeeds, otherwise False.
"""
cmd = self.command_builder('ntp source', disable=True)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19836
|
Ntp.default
|
train
|
def default(self):
"""Default the NTP source entry from the node.
Returns:
True if the operation succeeds, otherwise False.
"""
cmd = self.command_builder('ntp source', default=True)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19837
|
Ntp.set_source_interface
|
train
|
def set_source_interface(self, name):
"""Assign the NTP source on the node
Args:
name (string): The interface port that specifies the NTP source.
Returns:
True if the operation succeeds, otherwise False.
"""
cmd = self.command_builder('ntp source', value=name)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19838
|
Ntp.add_server
|
train
|
def add_server(self, name, prefer=False):
"""Add or update an NTP server entry to the node config
Args:
name (string): The IP address or FQDN of the NTP server.
prefer (bool): Sets the NTP server entry as preferred if True.
Returns:
True if the operation succeeds, otherwise False.
"""
if not name or re.match(r'^[\s]+$', name):
raise ValueError('ntp server name must be specified')
if prefer:
name = '%s prefer' % name
cmd = self.command_builder('ntp server', value=name)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19839
|
Ntp.remove_server
|
train
|
def remove_server(self, name):
"""Remove an NTP server entry from the node config
Args:
name (string): The IP address or FQDN of the NTP server.
Returns:
True if the operation succeeds, otherwise False.
"""
cmd = self.command_builder('no ntp server', value=name)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19840
|
Ntp.remove_all_servers
|
train
|
def remove_all_servers(self):
"""Remove all NTP server entries from the node config
Returns:
True if the operation succeeds, otherwise False.
"""
# 'no ntp' removes all server entries.
# For command_builder, disable command 'ntp' gives the desired command
cmd = self.command_builder('ntp', disable=True)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19841
|
System.get
|
train
|
def get(self):
"""Returns the system configuration abstraction
The System resource returns the following:
* hostname (str): The hostname value
Returns:
dict: Represents the node's system configuration
"""
resource = dict()
resource.update(self._parse_hostname())
resource.update(self._parse_iprouting())
resource.update(self._parse_banners())
return resource
|
python
|
{
"resource": ""
}
|
q19842
|
System._parse_hostname
|
train
|
def _parse_hostname(self):
"""Parses the global config and returns the hostname value
Returns:
dict: The configured value for hostname. The returned dict
object is intended to be merged into the resource dict
"""
value = 'localhost'
match = re.search(r'^hostname ([^\s]+)$', self.config, re.M)
if match:
value = match.group(1)
return dict(hostname=value)
|
python
|
{
"resource": ""
}
|
q19843
|
System._parse_banners
|
train
|
def _parse_banners(self):
"""Parses the global config and returns the value for both motd
and login banners.
Returns:
dict: The configure value for modtd and login banners. If the
banner is not set it will return a value of None for that
key. The returned dict object is intendd to be merged
into the resource dict
"""
motd_value = login_value = None
matches = re.findall('^banner\s+(login|motd)\s?$\n(.*?)$\nEOF$\n',
self.config, re.DOTALL | re.M)
for match in matches:
if match[0].strip() == "motd":
motd_value = match[1]
elif match[0].strip() == "login":
login_value = match[1]
return dict(banner_motd=motd_value, banner_login=login_value)
|
python
|
{
"resource": ""
}
|
q19844
|
System.set_hostname
|
train
|
def set_hostname(self, value=None, default=False, disable=False):
"""Configures the global system hostname setting
EosVersion:
4.13.7M
Args:
value (str): The hostname value
default (bool): Controls use of the default keyword
disable (bool): Controls the use of the no keyword
Returns:
bool: True if the commands are completed successfully
"""
cmd = self.command_builder('hostname', value=value, default=default,
disable=disable)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19845
|
System.set_iprouting
|
train
|
def set_iprouting(self, value=None, default=False, disable=False):
"""Configures the state of global ip routing
EosVersion:
4.13.7M
Args:
value(bool): True if ip routing should be enabled or False if
ip routing should be disabled
default (bool): Controls the use of the default keyword
disable (bool): Controls the use of the no keyword
Returns:
bool: True if the commands completed successfully otherwise False
"""
if value is False:
disable = True
cmd = self.command_builder('ip routing', value=value, default=default,
disable=disable)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
q19846
|
System.set_banner
|
train
|
def set_banner(self, banner_type, value=None, default=False,
disable=False):
"""Configures system banners
Args:
banner_type(str): banner to be changed (likely login or motd)
value(str): value to set for the banner
default (bool): Controls the use of the default keyword
disable (bool): Controls the use of the no keyword`
Returns:
bool: True if the commands completed successfully otherwise False
"""
command_string = "banner %s" % banner_type
if default is True or disable is True:
cmd = self.command_builder(command_string, value=None,
default=default, disable=disable)
return self.configure(cmd)
else:
if not value.endswith("\n"):
value = value + "\n"
command_input = dict(cmd=command_string, input=value)
return self.configure([command_input])
|
python
|
{
"resource": ""
}
|
q19847
|
Ipinterfaces.get
|
train
|
def get(self, name):
"""Returns the specific IP interface properties
The Ipinterface resource returns the following:
* name (str): The name of the interface
* address (str): The IP address of the interface in the form
of A.B.C.D/E
* mtu (int): The configured value for IP MTU.
Args:
name (string): The interface identifier to retrieve the
configuration for
Return:
A Python dictionary object of key/value pairs that represents
the current configuration of the node. If the specified
interface does not exist then None is returned.
"""
config = self.get_block('interface %s' % name)
if name[0:2] in ['Et', 'Po'] and not SWITCHPORT_RE.search(config,
re.M):
return None
resource = dict(name=name)
resource.update(self._parse_address(config))
resource.update(self._parse_mtu(config))
return resource
|
python
|
{
"resource": ""
}
|
q19848
|
Ipinterfaces._parse_address
|
train
|
def _parse_address(self, config):
"""Parses the config block and returns the ip address value
The provided configuration block is scaned and the configured value
for the IP address is returned as a dict object. If the IP address
value is not configured, then None is returned for the value
Args:
config (str): The interface configuration block to parse
Return:
dict: A dict object intended to be merged into the resource dict
"""
match = re.search(r'ip address ([^\s]+)', config)
value = match.group(1) if match else None
return dict(address=value)
|
python
|
{
"resource": ""
}
|
q19849
|
Ipinterfaces._parse_mtu
|
train
|
def _parse_mtu(self, config):
"""Parses the config block and returns the configured IP MTU value
The provided configuration block is scanned and the configured value
for the IP MTU is returned as a dict object. The IP MTU value is
expected to always be present in the provided config block
Args:
config (str): The interface configuration block to parse
Return:
dict: A dict object intended to be merged into the resource dict
"""
match = re.search(r'mtu (\d+)', config)
return dict(mtu=int(match.group(1)))
|
python
|
{
"resource": ""
}
|
q19850
|
Ipinterfaces.set_address
|
train
|
def set_address(self, name, value=None, default=False, disable=False):
""" Configures the interface IP address
Args:
name (string): The interface identifier to apply the interface
config to
value (string): The IP address and mask to set the interface to.
The value should be in the format of A.B.C.D/E
default (bool): Configures the address parameter to its default
value using the EOS CLI default command
disable (bool): Negates the address parameter value using the
EOS CLI no command
Returns:
True if the operation succeeds otherwise False.
"""
commands = ['interface %s' % name]
commands.append(self.command_builder('ip address', value=value,
default=default, disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19851
|
Ipinterfaces.set_mtu
|
train
|
def set_mtu(self, name, value=None, default=False, disable=False):
""" Configures the interface IP MTU
Args:
name (string): The interface identifier to apply the interface
config to
value (integer): The MTU value to set the interface to. Accepted
values include 68 to 65535
default (bool): Configures the mtu parameter to its default
value using the EOS CLI default command
disable (bool); Negate the mtu parameter value using the EOS
CLI no command
Returns:
True if the operation succeeds otherwise False.
Raises:
ValueError: If the value for MTU is not an integer value or
outside of the allowable range
"""
if value is not None:
value = int(value)
if not 68 <= value <= 65535:
raise ValueError('invalid mtu value')
commands = ['interface %s' % name]
commands.append(self.command_builder('mtu', value=value,
default=default, disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19852
|
Stp.get
|
train
|
def get(self):
"""Returns the spanning-tree configuration as a dict object
The dictionary object represents the entire spanning-tree
configuration derived from the nodes running config. This
includes both globally configuration attributes as well as
interfaces and instances. See the StpInterfaces and StpInstances
classes for the key/value pair definitions.
Note:
See the individual classes for detailed message structures
Returns:
A Python dictionary object of key/value pairs the represent
the entire supported spanning-tree configuration::
{
"mode": [mstp, none],
"interfaces": {...},
"instances": {...}
}
"""
return dict(interfaces=self.interfaces.getall(),
instances=self.instances.getall())
|
python
|
{
"resource": ""
}
|
q19853
|
Stp.set_mode
|
train
|
def set_mode(self, value=None, default=False, disable=False):
"""Configures the global spanning-tree mode
Note:
This configuration parameter is not defaultable
Args:
value (string): The value to configure the global spanning-tree
mode of operation. Valid values include 'mstp', 'none'
default (bool): Set the global spanning-tree mode to default.
disable (bool): Negate the global spanning-tree mode.
Returns:
True if the configuration operation succeeds otherwise False
Raises:
ValueError if the value is not in the accepted range
"""
if not default and not disable:
if value not in ['mstp', 'none']:
raise ValueError("Specified value must be one of "
"'mstp', 'none'")
cmds = self.command_builder('spanning-tree mode', value=value,
default=default, disable=disable)
return self.configure(cmds)
|
python
|
{
"resource": ""
}
|
q19854
|
StpInterfaces.get
|
train
|
def get(self, name):
"""Returns the specified interfaces STP configuration resource
The STP interface resource contains the following
* name (str): The interface name
* portfast (bool): The spanning-tree portfast admin state
* bpduguard (bool): The spanning-tree bpduguard admin state
* portfast_type (str): The spanning-tree portfast <type> value.
Valid values include "edge", "network", "normal"
Args:
name (string): The interface identifier to retrieve the config
for. Note: Spanning-tree interfaces are only supported on
Ethernet and Port-Channel interfaces
Returns:
dict: A resource dict object that represents the interface
configuration.
None: If the specified interace is not a STP port
"""
if not isvalidinterface(name):
return None
config = self.get_block(r'^interface\s%s$' % name)
resp = dict()
resp.update(self._parse_bpduguard(config))
resp.update(self._parse_portfast(config))
resp.update(self._parse_portfast_type(config))
return resp
|
python
|
{
"resource": ""
}
|
q19855
|
StpInterfaces.set_bpduguard
|
train
|
def set_bpduguard(self, name, value=False, default=False, disable=False):
"""Configures the bpduguard value for the specified interface
Args:
name (string): The interface identifier to configure. The name
must be the full interface name (eg Ethernet1, not Et1)
value (bool): True if bpduguard is enabled otherwise False
default (bool): Configures the bpduguard parameter to its default
value using the EOS CLI default config command
disable (bool): Negates the bpduguard parameter using the EOS
CLI no config command
Returns:
True if the command succeeds, otherwise False
Raises:
ValueError: Rasied if an invalid interface name is specified
TypeError: Raised if the value keyword argument does not evaluate
to a valid boolean
"""
value = 'enable' if value else 'disable'
string = 'spanning-tree bpduguard'
cmds = self.command_builder(string, value=value, default=default,
disable=disable)
return self.configure_interface(name, cmds)
|
python
|
{
"resource": ""
}
|
q19856
|
process_modules
|
train
|
def process_modules(modules):
'''Accepts dictionary of 'client' and 'api' modules and creates
the corresponding files.
'''
for mod in modules['client']:
directory = '%s/client_modules' % HERE
if not exists(directory):
makedirs(directory)
write_module_file(mod, directory, 'pyeapi')
for mod in modules['api']:
directory = '%s/api_modules' % HERE
if not exists(directory):
makedirs(directory)
write_module_file(mod, directory, 'pyeapi.api')
create_index(modules)
|
python
|
{
"resource": ""
}
|
q19857
|
create_index
|
train
|
def create_index(modules):
'''This takes a dict of modules and created the RST index file.'''
for key in modules.keys():
file_path = join(HERE, '%s_modules/_list_of_modules.rst' % key)
list_file = open(file_path, 'w')
# Write the generic header
list_file.write('%s\n' % AUTOGEN)
list_file.write('%s\n' % key.title())
list_file.write('=' * len(key))
list_file.write('\n\n')
list_file.write('.. toctree::\n')
list_file.write(' :maxdepth: 2\n\n')
for module in modules[key]:
list_file.write(' %s\n' % module)
|
python
|
{
"resource": ""
}
|
q19858
|
write_module_file
|
train
|
def write_module_file(name, path, package):
'''Creates an RST file for the module name passed in. It places it in the
path defined
'''
file_path = join(path, '%s.rst' % name)
mod_file = open(file_path, 'w')
mod_file.write('%s\n' % AUTOGEN)
mod_file.write('%s\n' % name.title())
mod_file.write('=' * len(name))
mod_file.write('\n\n')
mod_file.write('.. toctree::\n')
mod_file.write(' :maxdepth: 1\n\n')
mod_file.write('.. automodule:: %s.%s\n' % (package, name))
mod_file.write(' :members:\n')
mod_file.write(' :undoc-members:\n')
mod_file.write(' :show-inheritance:\n')
|
python
|
{
"resource": ""
}
|
q19859
|
import_module
|
train
|
def import_module(name):
""" Imports a module into the current runtime environment
This function emulates the Python import system that allows for
importing full path modules. It will break down the module and
import each part (or skip if it is already loaded in cache).
Args:
name (str): The name of the module to import. This should be
the full path of the module
Returns:
The module that was imported
"""
parts = name.split('.')
path = None
module_name = ''
fhandle = None
for index, part in enumerate(parts):
module_name = part if index == 0 else '%s.%s' % (module_name, part)
path = [path] if path is not None else path
try:
fhandle, path, descr = imp.find_module(part, path)
if module_name in sys.modules:
# since imp.load_module works like reload, need to be sure not
# to reload a previously loaded module
mod = sys.modules[module_name]
else:
mod = imp.load_module(module_name, fhandle, path, descr)
finally:
# lets be sure to clean up after ourselves
if fhandle:
fhandle.close()
return mod
|
python
|
{
"resource": ""
}
|
q19860
|
load_module
|
train
|
def load_module(name):
""" Attempts to load a module into the current environment
This function will load a module specified by name. The module
name is first checked to see if it is already loaded and will return
the module if it is. If the module hasn't been previously loaded
it will attempt to import it
Args:
name (str): Specifies the full name of the module. For instance
pyeapi.api.vlans
Returns:
The module that has been imported or retrieved from the sys modules
"""
try:
mod = None
mod = sys.modules[name]
except KeyError:
mod = import_module(name)
finally:
if not mod:
raise ImportError('unable to import module %s' % name)
return mod
|
python
|
{
"resource": ""
}
|
q19861
|
debug
|
train
|
def debug(text):
"""Log a message to syslog and stderr
Args:
text (str): The string object to print
"""
frame = inspect.currentframe().f_back
module = frame.f_globals['__name__']
func = frame.f_code.co_name
msg = "%s.%s: %s" % (module, func, text)
_LOGGER.debug(msg)
|
python
|
{
"resource": ""
}
|
q19862
|
make_iterable
|
train
|
def make_iterable(value):
"""Converts the supplied value to a list object
This function will inspect the supplied value and return an
iterable in the form of a list.
Args:
value (object): An valid Python object
Returns:
An iterable object of type list
"""
if sys.version_info <= (3, 0):
# Convert unicode values to strings for Python 2
if isinstance(value, unicode):
value = str(value)
if isinstance(value, str) or isinstance(value, dict):
value = [value]
if not isinstance(value, collections.Iterable):
raise TypeError('value must be an iterable object')
return value
|
python
|
{
"resource": ""
}
|
q19863
|
expand_range
|
train
|
def expand_range(arg, value_delimiter=',', range_delimiter='-'):
"""
Expands a delimited string of ranged integers into a list of strings
:param arg: The string range to expand
:param value_delimiter: The delimiter that separates values
:param range_delimiter: The delimiter that signifies a range of values
:return: An array of expanded string values
:rtype: list
"""
values = list()
expanded = arg.split(value_delimiter)
for item in expanded:
if range_delimiter in item:
start, end = item.split(range_delimiter)
_expand = range(int(start), int(end) + 1)
values.extend([str(x) for x in _expand])
else:
values.extend([item])
return [str(x) for x in values]
|
python
|
{
"resource": ""
}
|
q19864
|
collapse_range
|
train
|
def collapse_range(arg, value_delimiter=',', range_delimiter='-'):
"""
Collapses a list of values into a range set
:param arg: The list of values to collapse
:param value_delimiter: The delimiter that separates values
:param range_delimiter: The delimiter that separates a value range
:return: An array of collapsed string values
:rtype: list
"""
values = list()
expanded = arg.split(value_delimiter)
range_start = None
for v1, v2 in lookahead(expanded):
if v2:
v1 = int(v1)
v2 = int(v2)
if (v1 + 1) == v2:
if not range_start:
range_start = v1
elif range_start:
item = '{}{}{}'.format(range_start, range_delimiter, v1)
values.extend([item])
range_start = None
else:
values.extend([v1])
elif range_start:
item = '{}{}{}'.format(range_start, range_delimiter, v1)
values.extend([item])
range_start = None
else:
values.extend([v1])
return [str(x) for x in values]
|
python
|
{
"resource": ""
}
|
q19865
|
Switchports.get
|
train
|
def get(self, name):
"""Returns a dictionary object that represents a switchport
The Switchport resource returns the following:
* name (str): The name of the interface
* mode (str): The switchport mode value
* access_vlan (str): The switchport access vlan value
* trunk_native_vlan (str): The switchport trunk native vlan vlaue
* trunk_allowed_vlans (str): The trunk allowed vlans value
* trunk_groups (list): The list of trunk groups configured
Args:
name (string): The interface identifier to get. Note: Switchports
are only supported on Ethernet and Port-Channel interfaces
Returns:
dict: A Python dictionary object of key/value pairs that represent
the switchport configuration for the interface specified If
the specified argument is not a switchport then None
is returned
"""
config = self.get_block('interface %s' % name)
if 'no switchport\n' in config:
return
resource = dict(name=name)
resource.update(self._parse_mode(config))
resource.update(self._parse_access_vlan(config))
resource.update(self._parse_trunk_native_vlan(config))
resource.update(self._parse_trunk_allowed_vlans(config))
resource.update(self._parse_trunk_groups(config))
return resource
|
python
|
{
"resource": ""
}
|
q19866
|
Switchports._parse_mode
|
train
|
def _parse_mode(self, config):
"""Scans the specified config and parses the switchport mode value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport mode.
The dict returned is intended to be merged into the resource
dict
"""
value = re.search(r'switchport mode (\w+)', config, re.M)
return dict(mode=value.group(1))
|
python
|
{
"resource": ""
}
|
q19867
|
Switchports._parse_trunk_groups
|
train
|
def _parse_trunk_groups(self, config):
"""Scans the specified config and parses the trunk group values
Args:
config (str): The interface configuraiton blcok
Returns:
A dict object with the trunk group values that can be merged
into the resource dict
"""
values = re.findall(r'switchport trunk group ([^\s]+)', config, re.M)
return dict(trunk_groups=values)
|
python
|
{
"resource": ""
}
|
q19868
|
Switchports._parse_trunk_native_vlan
|
train
|
def _parse_trunk_native_vlan(self, config):
"""Scans the specified config and parse the trunk native vlan value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport trunk
native vlan value. The dict returned is intended to be
merged into the resource dict
"""
match = re.search(r'switchport trunk native vlan (\d+)', config)
return dict(trunk_native_vlan=match.group(1))
|
python
|
{
"resource": ""
}
|
q19869
|
Switchports._parse_trunk_allowed_vlans
|
train
|
def _parse_trunk_allowed_vlans(self, config):
"""Scans the specified config and parse the trunk allowed vlans value
Args:
config (str): The interface configuration block to scan
Returns:
dict: A Python dict object with the value of switchport trunk
allowed vlans value. The dict returned is intended to be
merged into the resource dict
"""
match = re.search(r'switchport trunk allowed vlan (.+)$', config, re.M)
return dict(trunk_allowed_vlans=match.group(1))
|
python
|
{
"resource": ""
}
|
q19870
|
Switchports.getall
|
train
|
def getall(self):
"""Returns a dict object to all Switchports
This method will return all of the configured switchports as a
dictionary object keyed by the interface identifier.
Returns:
A Python dictionary object that represents all configured
switchports in the current running configuration
"""
interfaces_re = re.compile(r'(?<=^interface\s)([Et|Po].+)$', re.M)
response = dict()
for name in interfaces_re.findall(self.config):
interface = self.get(name)
if interface:
response[name] = interface
return response
|
python
|
{
"resource": ""
}
|
q19871
|
Switchports.set_mode
|
train
|
def set_mode(self, name, value=None, default=False, disable=False):
"""Configures the switchport mode
Args:
name (string): The interface identifier to create the logical
layer 2 switchport for. The name must be the full interface
name and not an abbreviated interface name (eg Ethernet1, not
Et1)
value (string): The value to set the mode to. Accepted values
for this argument are access or trunk
default (bool): Configures the mode parameter to its default
value using the EOS CLI
disable (bool): Negate the mode parameter using the EOS CLI
Returns:
True if the create operation succeeds otherwise False.
"""
string = 'switchport mode'
command = self.command_builder(string, value=value, default=default,
disable=disable)
return self.configure_interface(name, command)
|
python
|
{
"resource": ""
}
|
q19872
|
Switchports.set_trunk_groups
|
train
|
def set_trunk_groups(self, intf, value=None, default=False, disable=False):
"""Configures the switchport trunk group value
Args:
intf (str): The interface identifier to configure.
value (str): The set of values to configure the trunk group
default (bool): Configures the trunk group default value
disable (bool): Negates all trunk group settings
Returns:
True if the config operation succeeds otherwise False
"""
if default:
cmd = 'default switchport trunk group'
return self.configure_interface(intf, cmd)
if disable:
cmd = 'no switchport trunk group'
return self.configure_interface(intf, cmd)
current_value = self.get(intf)['trunk_groups']
failure = False
value = make_iterable(value)
for name in set(value).difference(current_value):
if not self.add_trunk_group(intf, name):
failure = True
for name in set(current_value).difference(value):
if not self.remove_trunk_group(intf, name):
failure = True
return not failure
|
python
|
{
"resource": ""
}
|
q19873
|
Switchports.add_trunk_group
|
train
|
def add_trunk_group(self, intf, value):
"""Adds the specified trunk group to the interface
Args:
intf (str): The interface name to apply the trunk group to
value (str): The trunk group value to apply to the interface
Returns:
True if the operation as successfully applied otherwise false
"""
string = 'switchport trunk group {}'.format(value)
return self.configure_interface(intf, string)
|
python
|
{
"resource": ""
}
|
q19874
|
Switchports.remove_trunk_group
|
train
|
def remove_trunk_group(self, intf, value):
"""Removes a specified trunk group to the interface
Args:
intf (str): The interface name to remove the trunk group from
value (str): The trunk group value
Returns:
True if the operation as successfully applied otherwise false
"""
string = 'no switchport trunk group {}'.format(value)
return self.configure_interface(intf, string)
|
python
|
{
"resource": ""
}
|
q19875
|
BaseInterface._parse_description
|
train
|
def _parse_description(self, config):
"""Scans the specified config block and returns the description value
Args:
config (str): The interface config block to scan
Returns:
dict: Returns a dict object with the description value retrieved
from the config block. If the description value is not
configured, None is returned as the value. The returned dict
is intended to be merged into the interface resource dict.
"""
value = None
match = re.search(r'description (.+)$', config, re.M)
if match:
value = match.group(1)
return dict(description=value)
|
python
|
{
"resource": ""
}
|
q19876
|
BaseInterface.set_encapsulation
|
train
|
def set_encapsulation(self, name, vid, default=False, disable=False):
"""Configures the subinterface encapsulation value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
vid (int): The vlan id number
default (boolean): Specifies to default the subinterface
encapsulation
disable (boolean): Specifies to disable the subinterface
encapsulation
Returns:
True if the operation succeeds otherwise False is returned
"""
if '.' not in name:
raise NotImplementedError('parameter encapsulation can only be'
' set on subinterfaces')
if name[0:2] not in ['Et', 'Po']:
raise NotImplementedError('parameter encapsulation can only be'
' set on Ethernet and Port-Channel'
' subinterfaces')
commands = ['interface %s' % name]
commands.append(self.command_builder('encapsulation dot1q vlan',
str(vid), default=default,
disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19877
|
BaseInterface.set_description
|
train
|
def set_description(self, name, value=None, default=False, disable=False):
"""Configures the interface description
EosVersion:
4.13.7M
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (string): The value to set the description to.
default (boolean): Specifies to default the interface description
disable (boolean): Specifies to negate the interface description
Returns:
True if the operation succeeds otherwise False
"""
string = 'description'
commands = self.command_builder(string, value=value, default=default,
disable=disable)
return self.configure_interface(name, commands)
|
python
|
{
"resource": ""
}
|
q19878
|
BaseInterface.set_shutdown
|
train
|
def set_shutdown(self, name, default=False, disable=True):
"""Configures the interface shutdown state
Default configuration for set_shutdown is disable=True, meaning
'no shutdown'. Setting both default and disable to False will
effectively enable shutdown on the interface.
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
default (boolean): Specifies to default the interface shutdown
disable (boolean): Specifies to disable interface shutdown, i.e.
disable=True => no shutdown
Returns:
True if the operation succeeds otherwise False is returned
"""
commands = ['interface %s' % name]
commands.append(self.command_builder('shutdown', value=True,
default=default, disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19879
|
EthernetInterface._parse_flowcontrol_send
|
train
|
def _parse_flowcontrol_send(self, config):
"""Scans the config block and returns the flowcontrol send value
Args:
config (str): The interface config block to scan
Returns:
dict: Returns a dict object with the flowcontrol send value
retrieved from the config block. The returned dict object
is intended to be merged into the interface resource dict
"""
value = 'off'
match = re.search(r'flowcontrol send (\w+)$', config, re.M)
if match:
value = match.group(1)
return dict(flowcontrol_send=value)
|
python
|
{
"resource": ""
}
|
q19880
|
EthernetInterface._parse_flowcontrol_receive
|
train
|
def _parse_flowcontrol_receive(self, config):
"""Scans the config block and returns the flowcontrol receive value
Args:
config (str): The interface config block to scan
Returns:
dict: Returns a dict object with the flowcontrol receive value
retrieved from the config block. The returned dict object
is intended to be merged into the interface resource dict
"""
value = 'off'
match = re.search(r'flowcontrol receive (\w+)$', config, re.M)
if match:
value = match.group(1)
return dict(flowcontrol_receive=value)
|
python
|
{
"resource": ""
}
|
q19881
|
EthernetInterface.set_flowcontrol_send
|
train
|
def set_flowcontrol_send(self, name, value=None, default=False,
disable=False):
"""Configures the interface flowcontrol send value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (boolean): True if the interface should enable sending flow
control packets, otherwise False
default (boolean): Specifies to default the interface flow
control send value
disable (boolean): Specifies to disable the interface flow
control send value
Returns:
True if the operation succeeds otherwise False is returned
"""
return self.set_flowcontrol(name, 'send', value, default, disable)
|
python
|
{
"resource": ""
}
|
q19882
|
EthernetInterface.set_flowcontrol_receive
|
train
|
def set_flowcontrol_receive(self, name, value=None, default=False,
disable=False):
"""Configures the interface flowcontrol receive value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (boolean): True if the interface should enable receiving
flow control packets, otherwise False
default (boolean): Specifies to default the interface flow
control receive value
disable (boolean): Specifies to disable the interface flow
control receive value
Returns:
True if the operation succeeds otherwise False is returned
"""
return self.set_flowcontrol(name, 'receive', value, default, disable)
|
python
|
{
"resource": ""
}
|
q19883
|
EthernetInterface.set_flowcontrol
|
train
|
def set_flowcontrol(self, name, direction, value=None, default=False,
disable=False):
"""Configures the interface flowcontrol value
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
direction (string): one of either 'send' or 'receive'
value (boolean): True if the interface should enable flow control
packet handling, otherwise False
default (boolean): Specifies to default the interface flow control
send or receive value
disable (boolean): Specifies to disable the interface flow control
send or receive value
Returns:
True if the operation succeeds otherwise False is returned
"""
if value is not None:
if value not in ['on', 'off']:
raise ValueError('invalid flowcontrol value')
if direction not in ['send', 'receive']:
raise ValueError('invalid direction specified')
commands = ['interface %s' % name]
commands.append(self.command_builder('flowcontrol %s' % direction,
value=value, default=default,
disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19884
|
EthernetInterface.set_sflow
|
train
|
def set_sflow(self, name, value=None, default=False, disable=False):
"""Configures the sFlow state on the interface
Args:
name (string): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
value (boolean): True if sFlow should be enabled otherwise False
default (boolean): Specifies the default value for sFlow
disable (boolean): Specifies to disable sFlow
Returns:
True if the operation succeeds otherwise False is returned
"""
if value not in [True, False, None]:
raise ValueError
commands = ['interface %s' % name]
commands.append(self.command_builder('sflow enable', value=value,
default=default, disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19885
|
EthernetInterface.set_vrf
|
train
|
def set_vrf(self, name, vrf, default=False, disable=False):
"""Applies a VRF to the interface
Note: VRF being applied to interface must already exist in switch
config. Ethernet port must be in routed mode. This functionality
can also be handled in the VRF api.
Args:
name (str): The interface identifier. It must be a full
interface name (ie Ethernet, not Et)
vrf (str): The vrf name to be applied to the interface
default (bool): Specifies the default value for VRF
disable (bool): Specifies to disable VRF
Returns:
True if the operation succeeds otherwise False is returned
"""
commands = ['interface %s' % name]
commands.append(self.command_builder('vrf forwarding', vrf,
default=default, disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19886
|
PortchannelInterface.get_lacp_mode
|
train
|
def get_lacp_mode(self, name):
"""Returns the LACP mode for the specified Port-Channel interface
Args:
name(str): The Port-Channel interface name to return the LACP
mode for from the configuration
Returns:
The configured LACP mode for the interface. Valid mode values
are 'on', 'passive', 'active'
"""
members = self.get_members(name)
if not members:
return DEFAULT_LACP_MODE
for member in self.get_members(name):
match = re.search(r'channel-group\s\d+\smode\s(?P<value>.+)',
self.get_block('^interface %s' % member))
return match.group('value')
|
python
|
{
"resource": ""
}
|
q19887
|
PortchannelInterface.get_members
|
train
|
def get_members(self, name):
"""Returns the member interfaces for the specified Port-Channel
Args:
name(str): The Port-channel interface name to return the member
interfaces for
Returns:
A list of physical interface names that belong to the specified
interface
"""
grpid = re.search(r'(\d+)', name).group()
command = 'show port-channel %s all-ports' % grpid
config = self.node.enable(command, 'text')
return re.findall(r'\b(?!Peer)Ethernet[\d/]*\b',
config[0]['result']['output'])
|
python
|
{
"resource": ""
}
|
q19888
|
PortchannelInterface.set_members
|
train
|
def set_members(self, name, members, mode=None):
"""Configures the array of member interfaces for the Port-Channel
Args:
name(str): The Port-Channel interface name to configure the member
interfaces
members(list): The list of Ethernet interfaces that should be
member interfaces
mode(str): The LACP mode to configure the member interfaces to.
Valid values are 'on, 'passive', 'active'. When there are
existing channel-group members and their lacp mode differs
from this attribute, all of those members will be removed and
then re-added using the specified lacp mode. If this attribute
is omitted, the existing lacp mode will be used for new
member additions.
Returns:
True if the operation succeeds otherwise False
"""
commands = list()
grpid = re.search(r'(\d+)', name).group()
current_members = self.get_members(name)
lacp_mode = self.get_lacp_mode(name)
if mode and mode != lacp_mode:
lacp_mode = mode
self.set_lacp_mode(grpid, lacp_mode)
# remove members from the current port-channel interface
for member in set(current_members).difference(members):
commands.append('interface %s' % member)
commands.append('no channel-group %s' % grpid)
# add new member interfaces to the port-channel interface
for member in set(members).difference(current_members):
commands.append('interface %s' % member)
commands.append('channel-group %s mode %s' % (grpid, lacp_mode))
return self.configure(commands) if commands else True
|
python
|
{
"resource": ""
}
|
q19889
|
PortchannelInterface.set_lacp_mode
|
train
|
def set_lacp_mode(self, name, mode):
"""Configures the LACP mode of the member interfaces
Args:
name(str): The Port-Channel interface name to configure the
LACP mode
mode(str): The LACP mode to configure the member interfaces to.
Valid values are 'on, 'passive', 'active'
Returns:
True if the operation succeeds otherwise False
"""
if mode not in ['on', 'passive', 'active']:
return False
grpid = re.search(r'(\d+)', name).group()
remove_commands = list()
add_commands = list()
for member in self.get_members(name):
remove_commands.append('interface %s' % member)
remove_commands.append('no channel-group %s' % grpid)
add_commands.append('interface %s' % member)
add_commands.append('channel-group %s mode %s' % (grpid, mode))
return self.configure(remove_commands + add_commands)
|
python
|
{
"resource": ""
}
|
q19890
|
PortchannelInterface.set_lacp_fallback
|
train
|
def set_lacp_fallback(self, name, mode=None):
"""Configures the Port-Channel lacp_fallback
Args:
name(str): The Port-Channel interface name
mode(str): The Port-Channel LACP fallback setting
Valid values are 'disabled', 'static', 'individual':
* static - Fallback to static LAG mode
* individual - Fallback to individual ports
* disabled - Disable LACP fallback
Returns:
True if the operation succeeds otherwise False is returned
"""
if mode not in ['disabled', 'static', 'individual']:
return False
disable = True if mode == 'disabled' else False
commands = ['interface %s' % name]
commands.append(self.command_builder('port-channel lacp fallback',
value=mode, disable=disable))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19891
|
PortchannelInterface.set_lacp_timeout
|
train
|
def set_lacp_timeout(self, name, value=None):
"""Configures the Port-Channel LACP fallback timeout
The fallback timeout configures the period an interface in
fallback mode remains in LACP mode without receiving a PDU.
Args:
name(str): The Port-Channel interface name
value(int): port-channel lacp fallback timeout in seconds
Returns:
True if the operation succeeds otherwise False is returned
"""
commands = ['interface %s' % name]
string = 'port-channel lacp fallback timeout'
commands.append(self.command_builder(string, value=value))
return self.configure(commands)
|
python
|
{
"resource": ""
}
|
q19892
|
VxlanInterface._parse_source_interface
|
train
|
def _parse_source_interface(self, config):
""" Parses the conf block and returns the vxlan source-interface value
Parses the provided configuration block and returns the value of
vxlan source-interface. If the value is not configured, this method
will return DEFAULT_SRC_INTF instead.
Args:
config (str): The Vxlan config block to scan
Return:
dict: A dict object intended to be merged into the resource dict
"""
match = re.search(r'vxlan source-interface ([^\s]+)', config)
value = match.group(1) if match else self.DEFAULT_SRC_INTF
return dict(source_interface=value)
|
python
|
{
"resource": ""
}
|
q19893
|
VxlanInterface.add_vtep
|
train
|
def add_vtep(self, name, vtep, vlan=None):
"""Adds a new VTEP endpoint to the global or local flood list
EosVersion:
4.13.7M
Args:
name (str): The name of the interface to configure
vtep (str): The IP address of the remote VTEP endpoint to add
vlan (str): The VLAN ID associated with this VTEP. If the VLAN
keyword is used, then the VTEP is configured as a local flood
endpoing
Returns:
True if the command completes successfully
"""
if not vlan:
cmd = 'vxlan flood vtep add {}'.format(vtep)
else:
cmd = 'vxlan vlan {} flood vtep add {}'.format(vlan, vtep)
return self.configure_interface(name, cmd)
|
python
|
{
"resource": ""
}
|
q19894
|
VxlanInterface.remove_vtep
|
train
|
def remove_vtep(self, name, vtep, vlan=None):
"""Removes a VTEP endpoint from the global or local flood list
EosVersion:
4.13.7M
Args:
name (str): The name of the interface to configure
vtep (str): The IP address of the remote VTEP endpoint to add
vlan (str): The VLAN ID associated with this VTEP. If the VLAN
keyword is used, then the VTEP is configured as a local flood
endpoing
Returns:
True if the command completes successfully
"""
if not vlan:
cmd = 'vxlan flood vtep remove {}'.format(vtep)
else:
cmd = 'vxlan vlan {} flood vtep remove {}'.format(vlan, vtep)
return self.configure_interface(name, cmd)
|
python
|
{
"resource": ""
}
|
q19895
|
VxlanInterface.update_vlan
|
train
|
def update_vlan(self, name, vid, vni):
"""Adds a new vlan to vni mapping for the interface
EosVersion:
4.13.7M
Args:
vlan (str, int): The vlan id to map to the vni
vni (str, int): The vni value to use
Returns:
True if the command completes successfully
"""
cmd = 'vxlan vlan %s vni %s' % (vid, vni)
return self.configure_interface(name, cmd)
|
python
|
{
"resource": ""
}
|
q19896
|
Users.getall
|
train
|
def getall(self):
"""Returns all local users configuration as a resource dict
Returns:
dict: A dict of usernames with a nested resource dict object
"""
users = self.users_re.findall(self.config, re.M)
resources = dict()
for user in users:
resources.update(self._parse_username(user))
return resources
|
python
|
{
"resource": ""
}
|
q19897
|
Users._parse_username
|
train
|
def _parse_username(self, config):
"""Scans the config block and returns the username as a dict
Args:
config (str): The config block to parse
Returns:
dict: A resource dict that is intended to be merged into the
user resource
"""
(username, priv, role, nopass, fmt, secret, sshkey) = config
resource = dict()
resource['privilege'] = priv
resource['role'] = role
resource['nopassword'] = nopass == 'nopassword'
resource['format'] = fmt
resource['secret'] = secret
resource['sshkey'] = sshkey
return {username: resource}
|
python
|
{
"resource": ""
}
|
q19898
|
Users.create
|
train
|
def create(self, name, nopassword=None, secret=None, encryption=None):
"""Creates a new user on the local system.
Creating users requires either a secret (password) or the nopassword
keyword to be specified.
Args:
name (str): The name of the user to craete
nopassword (bool): Configures the user to be able to authenticate
without a password challenage
secret (str): The secret (password) to assign to this user
encryption (str): Specifies how the secret is encoded. Valid
values are "cleartext", "md5", "sha512". The default is
"cleartext"
Returns:
True if the operation was successful otherwise False
Raises:
TypeError: if the required arguments are not satisfied
"""
if secret is not None:
return self.create_with_secret(name, secret, encryption)
elif nopassword is True:
return self.create_with_nopassword(name)
else:
raise TypeError('either "nopassword" or "secret" must be '
'specified to create a user')
|
python
|
{
"resource": ""
}
|
q19899
|
Users.create_with_secret
|
train
|
def create_with_secret(self, name, secret, encryption):
"""Creates a new user on the local node
Args:
name (str): The name of the user to craete
secret (str): The secret (password) to assign to this user
encryption (str): Specifies how the secret is encoded. Valid
values are "cleartext", "md5", "sha512". The default is
"cleartext"
Returns:
True if the operation was successful otherwise False
"""
try:
encryption = encryption or DEFAULT_ENCRYPTION
enc = ENCRYPTION_MAP[encryption]
except KeyError:
raise TypeError('encryption must be one of "cleartext", "md5"'
' or "sha512"')
cmd = 'username %s secret %s %s' % (name, enc, secret)
return self.configure(cmd)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.