INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
BGP protocol attributes for get_route_tp Only IPv4 supported
def _get_bgp_route_attr(self, destination, vrf, next_hop, ip_version=4): """ BGP protocol attributes for get_route_tp Only IPv4 supported """ CMD_SHIBNV = 'show ip bgp neighbors vrf {vrf} | include "is {neigh}"' search_re_dict = { "aspath": { ...
Only IPv4 supported vrf aware longer_prefixes parameter ready
def get_route_to(self, destination="", protocol=""): """ Only IPv4 supported, vrf aware, longer_prefixes parameter ready """ longer_pref = "" # longer_prefixes support, for future use vrf = "" ip_version = None try: ip_version = IPNetwork(destination...
Standardized method of creating a Netmiko connection using napalm attributes.
def _netmiko_open(self, device_type, netmiko_optional_args=None): """Standardized method of creating a Netmiko connection using napalm attributes.""" if netmiko_optional_args is None: netmiko_optional_args = {} try: self._netmiko_device = ConnectHandler( d...
Will load a templated configuration on the device.
def load_template( self, template_name, template_source=None, template_path=None, **template_vars ): """ Will load a templated configuration on the device. :param cls: Instance of the driver class. :param template_name: Identifies the template name. :param template_s...
Executes traceroute on the device and returns a dictionary with the result.
def traceroute( self, destination, source=c.TRACEROUTE_SOURCE, ttl=c.TRACEROUTE_TTL, timeout=c.TRACEROUTE_TIMEOUT, vrf=c.TRACEROUTE_VRF, ): """ Executes traceroute on the device and returns a dictionary with the result. :param destination: Hos...
Return a compliance report.
def compliance_report(self, validation_file=None, validation_source=None): """ Return a compliance report. Verify that the device complies with the given validation file and writes a compliance report file. See https://napalm.readthedocs.io/en/latest/validate/index.html. :param...
Expose the helper function within this class.
def _canonical_int(self, interface): """Expose the helper function within this class.""" if self.use_canonical_interface is True: return napalm.base.helpers.canonical_interface_name( interface, addl_name_map=None ) else: return interface
Open the connection with the device.
def open(self): """Open the connection with the device.""" try: self.device.open() except ConnectTimeoutError as cte: raise ConnectionException(cte.msg) self.device.timeout = self.timeout self.device._conn._session.transport.set_keepalive(self.keepalive) ...
Close the connection.
def close(self): """Close the connection.""" if not self.lock_disable and self.session_config_lock: self._unlock() self.device.close()
Lock the config DB.
def _lock(self): """Lock the config DB.""" if not self.locked: try: self.device.cu.lock() self.locked = True except JnprLockError as jle: raise LockError(py23_compat.text_type(jle))
Unlock the config DB.
def _unlock(self): """Unlock the config DB.""" if self.locked: try: self.device.cu.unlock() self.locked = False except JnrpUnlockError as jue: raise UnlockError(jue.messsage)
This allows you to construct an arbitrary RPC call to retreive common stuff. For example: Configuration: get: <get - configuration/ > Interface information: get: <get - interface - information/ > A particular interfacece information: get: <get - interface - information/ > child: <interface - name > ge - 0/ 0/ 0</ inter...
def _rpc(self, get, child=None, **kwargs): """ This allows you to construct an arbitrary RPC call to retreive common stuff. For example: Configuration: get: "<get-configuration/>" Interface information: get: "<get-interface-information/>" A particular interfacece information: ...
Open the candidate config and merge.
def load_replace_candidate(self, filename=None, config=None): """Open the candidate config and merge.""" self.config_replace = True self._load_candidate(filename, config, True)
Open the candidate config and replace.
def load_merge_candidate(self, filename=None, config=None): """Open the candidate config and replace.""" self.config_replace = False self._load_candidate(filename, config, False)
Commit configuration.
def commit_config(self, message=""): """Commit configuration.""" commit_args = {"comment": message} if message else {} self.device.cu.commit(ignore_warning=self.ignore_warning, **commit_args) if not self.lock_disable and not self.session_config_lock: self._unlock()
Discard changes ( rollback 0 ).
def discard_config(self): """Discard changes (rollback 0).""" self.device.cu.rollback(rb_id=0) if not self.lock_disable and not self.session_config_lock: self._unlock()
Return interfaces details.
def get_interfaces(self): """Return interfaces details.""" result = {} interfaces = junos_views.junos_iface_table(self.device) interfaces.get() interfaces_logical = junos_views.junos_logical_iface_table(self.device) interfaces_logical.get() # convert all the tup...
Return interfaces counters.
def get_interfaces_counters(self): """Return interfaces counters.""" query = junos_views.junos_iface_counter_table(self.device) query.get() interface_counters = {} for interface, counters in query.items(): interface_counters[interface] = { k: v if v is...
Return environment details.
def get_environment(self): """Return environment details.""" environment = junos_views.junos_environment_table(self.device) routing_engine = junos_views.junos_routing_engine_table(self.device) temperature_thresholds = junos_views.junos_temperature_thresholds(self.device) power_su...
Function to derive address family from a junos table name.
def _get_address_family(table, instance): """ Function to derive address family from a junos table name. :params table: The name of the routing table :returns: address family """ address_family_mapping = {"inet": "ipv4", "inet6": "ipv6", "inetflow": "flow"} if in...
Detailed view of the LLDP neighbors.
def get_lldp_neighbors_detail(self, interface=""): """Detailed view of the LLDP neighbors.""" lldp_neighbors = defaultdict(list) lldp_table = junos_views.junos_lldp_neighbors_detail_table(self.device) if not interface: try: lldp_table.get() except ...
Execute raw CLI commands and returns their output.
def cli(self, commands): """Execute raw CLI commands and returns their output.""" cli_output = {} def _count(txt, none): # Second arg for consistency only. noqa """ Return the exact output, as Junos displays e.g.: > show system processes extensiv...
Return BGP configuration.
def get_bgp_config(self, group="", neighbor=""): """Return BGP configuration.""" def _check_nhs(policies, nhs_policies): if not isinstance(policies, list): # Make it a list if it is a single policy policies = [policies] # Return True if "next-hop ...
Detailed view of the BGP neighbors operational data.
def get_bgp_neighbors_detail(self, neighbor_address=""): """Detailed view of the BGP neighbors operational data.""" bgp_neighbors = {} default_neighbor_details = { "up": False, "local_as": 0, "remote_as": 0, "router_id": "", "local_addr...
Return the ARP table.
def get_arp_table(self, vrf=""): """Return the ARP table.""" # could use ArpTable # from jnpr.junos.op.phyport import ArpTable # and simply use it # but # we need: # - filters # - group by VLAN ID # - hostname & TTE fields as well if ...
Return the IPv6 neighbors table.
def get_ipv6_neighbors_table(self): """Return the IPv6 neighbors table.""" ipv6_neighbors_table = [] ipv6_neighbors_table_raw = junos_views.junos_ipv6_neighbors_table(self.device) ipv6_neighbors_table_raw.get() ipv6_neighbors_table_items = ipv6_neighbors_table_raw.items() ...
Return NTP stats ( associations ).
def get_ntp_stats(self): """Return NTP stats (associations).""" # NTP Peers does not have XML RPC defined # thus we need to retrieve raw text and parse... # :( ntp_stats = [] REGEX = ( r"^\s?(\+|\*|x|-)?([a-zA-Z0-9\.+-:]+)" r"\s+([a-zA-Z0-9\.]+)\...
Return the configured IP addresses.
def get_interfaces_ip(self): """Return the configured IP addresses.""" interfaces_ip = {} interface_table = junos_views.junos_ip_interfaces_table(self.device) interface_table.get() interface_table_items = interface_table.items() _FAMILY_VMAP_ = { "inet": "ip...
Return the MAC address table.
def get_mac_address_table(self): """Return the MAC address table.""" mac_address_table = [] switch_style = self.device.facts.get("switch_style", "") if switch_style == "VLAN_L2NG": mac_table = junos_views.junos_mac_address_table_switch_l2ng(self.device) elif switch_s...
Return route details to a specific destination learned from a certain protocol.
def get_route_to(self, destination="", protocol=""): """Return route details to a specific destination, learned from a certain protocol.""" routes = {} if not isinstance(destination, py23_compat.string_types): raise TypeError("Please specify a valid destination!") if protoc...
Return the SNMP configuration.
def get_snmp_information(self): """Return the SNMP configuration.""" snmp_information = {} snmp_config = junos_views.junos_snmp_config_table(self.device) snmp_config.get() snmp_items = snmp_config.items() if not snmp_items: return snmp_information s...
get root user password.
def _get_root(self): """get root user password.""" _DEFAULT_USER_DETAILS = {"level": 20, "password": "", "sshkeys": []} root = {} root_table = junos_views.junos_root_table(self.device) root_table.get() root_items = root_table.items() for user_entry in root_items: ...
Return the configuration of the users.
def get_users(self): """Return the configuration of the users.""" users = {} _JUNOS_CLASS_CISCO_PRIVILEGE_LEVEL_MAP = { "super-user": 15, "superuser": 15, "operator": 5, "read-only": 1, "unauthorized": 0, } _DEFAULT_US...
Return optics information.
def get_optics(self): """Return optics information.""" optics_table = junos_views.junos_intf_optics_table(self.device) optics_table.get() optics_items = optics_table.items() # optics_items has no lane information, so we need to re-format data # inserting lane 0 for all o...
Dynamically create PY3 version of the file by re - writing unicode to str.
def _preprocess_yml(path): """Dynamically create PY3 version of the file by re-writing 'unicode' to 'str'.""" with open(path) as f: tmp_yaml = f.read() return re.sub(r"unicode", "str", tmp_yaml)
Use CiscoConfParse to find parent lines that contain a specific child line.
def cisco_conf_parse_parents(parent, child, config): """ Use CiscoConfParse to find parent lines that contain a specific child line. :param parent: The parent line to search for :param child: The child line required under the given parent :param config: The device running/startup config """ ...
Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to show run | section <cfg_section >
def cisco_conf_parse_objects(cfg_section, config): """ Use CiscoConfParse to find and return a section of Cisco IOS config. Similar to "show run | section <cfg_section>" :param cfg_section: The section of the config to return eg. "router bgp" :param config: The running/startup config of the device ...
RegEx search for pattern in text. Will try to match the data type of the default value or return the default value if no match is found. This is to parse IOS config like below: regex_find_txt ( r remote - as ( 65000 ) neighbor 10. 0. 0. 1 remote - as 65000 default = 0 ) RETURNS: 65001
def regex_find_txt(pattern, text, default=""): """"" RegEx search for pattern in text. Will try to match the data type of the "default" value or return the default value if no match is found. This is to parse IOS config like below: regex_find_txt(r"remote-as (65000)", "neighbor 10.0.0.1 remote-as 65...
Applies a TextFSM template over a raw text and return the matching table.
def textfsm_extractor(cls, template_name, raw_text): """ Applies a TextFSM template over a raw text and return the matching table. Main usage of this method will be to extract data form a non-structured output from a network device and return the values in a table format. :param cls: Instance of t...
Converts a raw string to a valid IP address. Optional version argument will detect that \ object matches specified version.
def ip(addr, version=None): """ Converts a raw string to a valid IP address. Optional version argument will detect that \ object matches specified version. Motivation: the groups of the IP addreses may contain leading zeros. IPv6 addresses can \ contain sometimes uppercase characters. E.g.: 2001:0d...
Convert AS Number to standardized asplain notation as an integer.
def as_number(as_number_val): """Convert AS Number to standardized asplain notation as an integer.""" as_number_str = py23_compat.text_type(as_number_val) if "." in as_number_str: big, little = as_number_str.split(".") return (int(big) << 16) + int(little) else: return int(as_num...
Split an interface name based on first digit slash or space match.
def split_interface(intf_name): """Split an interface name based on first digit, slash, or space match.""" head = intf_name.rstrip(r"/\0123456789. ") tail = intf_name[len(head) :].lstrip() return (head, tail)
Function to return an interface s canonical name ( fully expanded name ).
def canonical_interface_name(interface, addl_name_map=None): """Function to return an interface's canonical name (fully expanded name). Use of explicit matches used to indicate a clear understanding on any potential match. Regex and other looser matching methods were not implmented to avoid false posit...
Function to return an abbreviated representation of the interface name.
def abbreviated_interface_name(interface, addl_name_map=None, addl_reverse_map=None): """Function to return an abbreviated representation of the interface name. :param interface: The interface you are attempting to abbreviate. :param addl_name_map (optional): A dict containing key/value pairs that updates ...
Close the connection to the device and do the necessary cleanup.
def close(self): """Close the connection to the device and do the necessary cleanup.""" # Return file prompt quiet to the original state if self.auto_file_prompt and self.prompt_quiet_changed is True: self.device.send_config_set(["no file prompt quiet"]) self.prompt_quie...
Wrapper for self. device. send. command ().
def _send_command(self, command): """Wrapper for self.device.send.command(). If command is a list will iterate through commands until valid command. """ try: if isinstance(command, list): for cmd in command: output = self.device.send_comma...
Returns a flag with the state of the connection.
def is_alive(self): """Returns a flag with the state of the connection.""" null = chr(0) if self.device is None: return {"is_alive": False} if self.transport == "telnet": try: # Try sending IAC + NOP (IAC is telnet way of sending command ...
Filter out strings that should not show up in the diff.
def _normalize_compare_config(self, diff): """Filter out strings that should not show up in the diff.""" ignore_strings = [ "Contextual Config Diffs", "No changes were found", "ntp clock-period", ] if self.auto_file_prompt: ignore_strings.a...
Make the compare config output look better.
def _normalize_merge_diff_incr(diff): """Make the compare config output look better. Cisco IOS incremental-diff output No changes: !List of Commands: end !No changes were found """ new_diff = [] changes_found = False for line in diff.spl...
Make compare_config () for merge look similar to replace config diff.
def _normalize_merge_diff(diff): """Make compare_config() for merge look similar to replace config diff.""" new_diff = [] for line in diff.splitlines(): # Filter blank lines and prepend +sign if line.strip(): new_diff.append("+" + line) if new_diff...
show archive config differences <base_file > <new_file >.
def compare_config(self): """ show archive config differences <base_file> <new_file>. Default operation is to compare system:running-config to self.candidate_cfg """ # Set defaults base_file = "running-config" base_file_system = "system:" if self.config_r...
Decorator to toggle file prompt quiet for methods that perform file operations.
def _file_prompt_quiet(f): """Decorator to toggle 'file prompt quiet' for methods that perform file operations.""" @functools.wraps(f) def wrapper(self, *args, **kwargs): if not self.prompt_quiet_configured: if self.auto_file_prompt: # disable fil...
Special handler for hostname change on commit operation. Also handles username removal which prompts for confirmation ( username removal prompts for each user... )
def _commit_handler(self, cmd): """ Special handler for hostname change on commit operation. Also handles username removal which prompts for confirmation (username removal prompts for each user...) """ current_prompt = self.device.find_prompt().strip() terminating_char = ...
If replacement operation perform configure replace for the entire config.
def commit_config(self, message=""): """ If replacement operation, perform 'configure replace' for the entire config. If merge operation, perform copy <file> running-config. """ if message: raise NotImplementedError( "Commit message not implemented fo...
Set candidate_cfg to current running - config. Erase the merge_cfg file.
def _discard_config(self): """Set candidate_cfg to current running-config. Erase the merge_cfg file.""" discard_candidate = "copy running-config {}".format( self._gen_full_path(self.candidate_cfg) ) discard_merge = "copy null: {}".format(self._gen_full_path(self.merge_cfg)) ...
Rollback configuration to filename or to self. rollback_cfg file.
def rollback(self): """Rollback configuration to filename or to self.rollback_cfg file.""" filename = self.rollback_cfg cfg_file = self._gen_full_path(filename) if not self._check_file_exists(cfg_file): raise ReplaceConfigException("Rollback config file does not exist") ...
Use Netmiko InlineFileTransfer ( TCL ) to transfer file or config to remote device.
def _inline_tcl_xfer( self, source_file=None, source_config=None, dest_file=None, file_system=None ): """ Use Netmiko InlineFileTransfer (TCL) to transfer file or config to remote device. Return (status, msg) status = boolean msg = details on what happened ""...
SCP file to remote device.
def _scp_file(self, source_file, dest_file, file_system): """ SCP file to remote device. Return (status, msg) status = boolean msg = details on what happened """ return self._xfer_file( source_file=source_file, dest_file=dest_file, ...
Transfer file to remote device.
def _xfer_file( self, source_file=None, source_config=None, dest_file=None, file_system=None, TransferClass=FileTransfer, ): """Transfer file to remote device. By default, this will use Secure Copy if self.inline_transfer is set, then will use ...
Cleanup actions on send_command () for NAPALM getters.
def _send_command_postprocess(output): """ Cleanup actions on send_command() for NAPALM getters. Remove "Load for five sec; one minute if in output" Remove "Time source is" """ output = re.sub(r"^Load for five secs.*$", "", output, flags=re.M) output = re.sub(r"^...
Get interface ip details.
def get_interfaces_ip(self): """ Get interface ip details. Returns a dict of dicts Example Output: { u'FastEthernet8': { 'ipv4': { u'10.66.43.169': { 'prefix_length': 22}}}, u'Loopback555': { 'ipv4': { u'192.168.1.1': { 'prefix_length': 24}}, ...
Parse BGP config params into a dict: param group =:: param neighbor =:
def get_bgp_config(self, group="", neighbor=""): """ Parse BGP config params into a dict :param group='': :param neighbor='': """ bgp_config = {} def build_prefix_limit(af_table, limit, prefix_percent, prefix_timeout): prefix_limit = {} ...
BGP neighbor information.
def get_bgp_neighbors(self): """BGP neighbor information. Currently no VRF support. Supports both IPv4 and IPv6. """ supported_afi = ["ipv4", "ipv6"] bgp_neighbor_data = dict() bgp_neighbor_data["global"] = {} # get summary output from device cmd_bgp_al...
Return interface counters and errors.
def get_interfaces_counters(self): """ Return interface counters and errors. 'tx_errors': int, 'rx_errors': int, 'tx_discards': int, 'rx_discards': int, 'tx_octets': int, 'rx_octets': int, 'tx_unicast_packets': int, 'rx_unicast_packets': i...
Get environment facts.
def get_environment(self): """ Get environment facts. power and fan are currently not implemented cpu is using 1-minute average cpu hard-coded to cpu0 (i.e. only a single CPU) """ environment = {} cpu_cmd = "show proc cpu" mem_cmd = "show memory s...
Implementation of get_ntp_peers for IOS.
def get_ntp_peers(self): """Implementation of get_ntp_peers for IOS.""" ntp_stats = self.get_ntp_stats() return { ntp_peer.get("remote"): {} for ntp_peer in ntp_stats if ntp_peer.get("remote") }
Implementation of get_ntp_servers for IOS.
def get_ntp_servers(self): """Implementation of get_ntp_servers for IOS. Returns the NTP servers configuration as dictionary. The keys of the dictionary represent the IP Addresses of the servers. Inner dictionaries do not have yet any available keys. Example:: { ...
Implementation of get_ntp_stats for IOS.
def get_ntp_stats(self): """Implementation of get_ntp_stats for IOS.""" ntp_stats = [] command = "show ntp associations" output = self._send_command(command) for line in output.splitlines(): # Skip first two lines and last line of command output if line ...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table having the following keys * mac ( string ) * interface ( string ) * vlan ( int ) * active ( boolean ) * static ( boolean ) * moves ( int ) * last_move ( float )
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
Returns a dict of dicts
def get_snmp_information(self): """ Returns a dict of dicts Example Output: { 'chassis_id': u'Asset Tag 54670', 'community': { u'private': { 'acl': u'12', 'mode': u'rw'}, u'public': { 'acl': u'11', 'mode': u'ro'}, u'publ...
Returns a dictionary with the configured users. The keys of the main dictionary represents the username. The values represent the details of the user represented by the following keys:
def get_users(self): """ Returns a dictionary with the configured users. The keys of the main dictionary represents the username. The values represent the details of the user, represented by the following keys: * level (int) * password (str) *...
Execute ping on the device and returns a dictionary with the result.
def ping( self, destination, source=C.PING_SOURCE, ttl=C.PING_TTL, timeout=C.PING_TIMEOUT, size=C.PING_SIZE, count=C.PING_COUNT, vrf=C.PING_VRF, ): """ Execute ping on the device and returns a dictionary with the result. Output...
Get IPv6 neighbors table information. Return a list of dictionaries having the following set of keys: * interface ( string ) * mac ( string ) * ip ( string ) * age ( float ) in seconds * state ( string ) For example:: [ { interface: MgmtEth0/ RSP0/ CPU0/ 0 mac: 5c: 5e: ab: da: 3c: f0 ip: 2001: db8: 1: 1:: 1 age: 145449...
def get_ipv6_neighbors_table(self): """ Get IPv6 neighbors table information. Return a list of dictionaries having the following set of keys: * interface (string) * mac (string) * ip (string) * age (float) in seconds * state (string) ...
Implementation of NAPALM method open.
def open(self): """Implementation of NAPALM method open.""" try: connection = self.transport_class( host=self.hostname, username=self.username, password=self.password, timeout=self.timeout, **self.eapi_kwargs ...
Converts running - config HEREDOC into EAPI JSON dict
def _multiline_convert(config, start="banner login", end="EOF", depth=1): """Converts running-config HEREDOC into EAPI JSON dict""" ret = list(config) # Don't modify list in-place try: s = ret.index(start) e = s while depth: e = ret.index(end,...
EOS has the concept of multi - line mode comments shown in the running - config as being inside a config stanza ( router bgp ACL definition etc ) and beginning with the normal level of spaces and !! followed by comments.
def _mode_comment_convert(commands): """ EOS has the concept of multi-line mode comments, shown in the running-config as being inside a config stanza (router bgp, ACL definition, etc) and beginning with the normal level of spaces and '!!', followed by comments. Unfortunately, py...
Implementation of NAPALM method commit_config.
def commit_config(self, message=""): """Implementation of NAPALM method commit_config.""" if message: raise NotImplementedError( "Commit message not implemented for this platform" ) commands = [ "copy startup-config flash:rollback-0", ...
Implementation of NAPALM method get_bgp_config.
def get_bgp_config(self, group="", neighbor=""): """Implementation of NAPALM method get_bgp_config.""" _GROUP_FIELD_MAP_ = { "type": "type", "multipath": "multipath", "apply-groups": "apply_groups", "remove-private-as": "remove_private_as", "eb...
get_network_instances implementation for EOS.
def get_network_instances(self, name=""): """get_network_instances implementation for EOS.""" output = self._show_vrf() vrfs = {} all_vrf_interfaces = {} for vrf in output: if ( vrf.get("route_distinguisher", "") == "<not set>" or vrf....
Execute ping on the device and returns a dictionary with the result. Output dictionary has one of following keys: * success * error In case of success inner dictionary will have the followin keys: * probes_sent ( int ) * packet_loss ( int ) * rtt_min ( float ) * rtt_max ( float ) * rtt_avg ( float ) * rtt_stddev ( floa...
def ping( self, destination, source=c.PING_SOURCE, ttl=c.PING_TTL, timeout=c.PING_TIMEOUT, size=c.PING_SIZE, count=c.PING_COUNT, vrf=c.PING_VRF, ): """ Execute ping on the device and returns a dictionary with the result. Output ...
Recursively iterate through values in nested lists.
def empty_tree(input_list): """Recursively iterate through values in nested lists.""" for item in input_list: if not isinstance(item, list) or not empty_tree(item): return False return True
Create documentation for Ansible modules.
def build_napalm_ansible_module_docs(app): """Create documentation for Ansible modules.""" # Add script to clone napalm-ansible repo status = subprocess.call( "./build-ansible-module-docs.sh", stdout=sys.stdout, stderr=sys.stderr ) if status != 0: print("Something bad happened when...
Build the getters support matrix.
def build_getters_support_matrix(app): """Build the getters support matrix.""" status = subprocess.call("./test.sh", stdout=sys.stdout, stderr=sys.stderr) if status != 0: print("Something bad happened when processing the test reports.") sys.exit(-1) drivers = set() matrix = { ...
Initial run to figure out what VRF s are available Decided to get this one from Configured - section because bulk - getting all instance - data to do the same could get ridiculously heavy Assuming we re always interested in the DefaultVRF
def get_bgp_neighbors(self): def generate_vrf_query(vrf_name): """ Helper to provide XML-query for the VRF-type we're interested in. """ if vrf_name == "global": rpc_command = "<Get><Operational><BGP><InstanceTable><Instance><Naming>\ ...
Check for Netmiko arguments that were passed in as NAPALM optional arguments.
def netmiko_args(optional_args): """Check for Netmiko arguments that were passed in as NAPALM optional arguments. Return a dictionary of these optional args that will be passed into the Netmiko ConnectHandler call. """ fields = py23_compat.argspec(BaseConnection.__init__) args = fields[0] ...
Decorator that ensures Netmiko connection exists.
def ensure_netmiko_conn(func): """Decorator that ensures Netmiko connection exists.""" def wrap_function(self, filename=None, config=None): try: netmiko_object = self._netmiko_device if netmiko_object is None: raise AttributeError() except AttributeError:...
The merge diff is not necessarily what needs to be loaded for example under NTP even though the ntp commit command might be alread configured it is mandatory to be sent otherwise it won t take the new configuration - see: https:// github. com/ napalm - automation/ napalm - nxos/ issues/ 59 therefore this method will re...
def _get_merge_diff(self): """ The merge diff is not necessarily what needs to be loaded for example under NTP, even though the 'ntp commit' command might be alread configured, it is mandatory to be sent otherwise it won't take the new configuration - see: https://github....
Get a diff between running config and a proposed file.
def _get_diff(self): """Get a diff between running config and a proposed file.""" diff = [] self._create_sot_file() diff_out = self._send_command( "show diff rollback-patch file {} file {}".format( "sot_file", self.candidate_cfg ), raw_...
Create Source of Truth file to compare.
def _create_sot_file(self): """Create Source of Truth file to compare.""" # Bug on on NX-OS 6.2.16 where overwriting sot_file would take exceptionally long time # (over 12 minutes); so just delete the sot_file try: self._delete_file(filename="sot_file") except Except...
Execute ping on the device and returns a dictionary with the result. Output dictionary has one of following keys: * success * error In case of success inner dictionary will have the followin keys: * probes_sent ( int ) * packet_loss ( int ) * rtt_min ( float ) * rtt_max ( float ) * rtt_avg ( float ) * rtt_stddev ( floa...
def ping( self, destination, source=c.PING_SOURCE, ttl=c.PING_TTL, timeout=c.PING_TIMEOUT, size=c.PING_SIZE, count=c.PING_COUNT, vrf=c.PING_VRF, ): """ Execute ping on the device and returns a dictionary with the result. Output ...
IOS implementation of get_lldp_neighbors.
def get_lldp_neighbors(self): """IOS implementation of get_lldp_neighbors.""" lldp = {} neighbors_detail = self.get_lldp_neighbors_detail() for intf_name, entries in neighbors_detail.items(): lldp[intf_name] = [] for lldp_entry in entries: hostname...
Wrapper for NX - API show method.
def _send_command(self, command, raw_text=False): """ Wrapper for NX-API show method. Allows more code sharing between NX-API and SSH. """ return self.device.show(command, raw_text=raw_text)
Some fields such uptime are returned as: 23week ( s ) 3day ( s ) This method will determine the epoch of the event. e. g.: 23week ( s ) 3day ( s ) - > 1462248287
def _compute_timestamp(stupid_cisco_output): """ Some fields such `uptime` are returned as: 23week(s) 3day(s) This method will determine the epoch of the event. e.g.: 23week(s) 3day(s) -> 1462248287 """ if not stupid_cisco_output or stupid_cisco_output == "never": ...
Inconsistent behavior: { TABLE_intf: [ { ROW_intf: { vs { TABLE_mac_address: { ROW_mac_address: [ { vs { TABLE_vrf: { ROW_vrf: { TABLE_adj: { ROW_adj: {
def _get_table_rows(parent_table, table_name, row_name): """ Inconsistent behavior: {'TABLE_intf': [{'ROW_intf': { vs {'TABLE_mac_address': {'ROW_mac_address': [{ vs {'TABLE_vrf': {'ROW_vrf': {'TABLE_adj': {'ROW_adj': { """ if parent_table is None:...
af_name_dict = { af - id: { safi: af - name } af - id: { safi: af - name } af - id: { safi: af - name } }
def get_bgp_neighbors(self): results = {} bgp_state_dict = { "Idle": {"is_up": False, "is_enabled": True}, "Active": {"is_up": False, "is_enabled": True}, "Open": {"is_up": False, "is_enabled": True}, "Established": {"is_up": True, "is_enabled": True}, ...
get_network_instances implementation for NX - OS
def get_network_instances(self, name=""): """ get_network_instances implementation for NX-OS """ # command 'show vrf detail' returns all VRFs with detailed information # format: list of dictionaries with keys such as 'vrf_name' and 'rd' command = "show vrf detail" vrf_table_raw ...
Searches for a class derived form the base NAPALM class NetworkDriver in a specific library. The library name must repect the following pattern: napalm_ [ DEVICE_OS ]. NAPALM community supports a list of devices and provides the corresponding libraries ; for full reference please refer to the Supported Network Operatio...
def get_network_driver(name, prepend=True): """ Searches for a class derived form the base NAPALM class NetworkDriver in a specific library. The library name must repect the following pattern: napalm_[DEVICE_OS]. NAPALM community supports a list of devices and provides the corresponding libraries; for ...
Load a config for the device.
def main(config_file): """Load a config for the device.""" if not (os.path.exists(config_file) and os.path.isfile(config_file)): msg = "Missing or invalid config file {0}".format(config_file) raise ValueError(msg) print("Loading config file {0}.".format(config_file)) # Use the appropr...
Return wether an OC attribute has been defined or not.
def oc_attr_isdefault(o): """Return wether an OC attribute has been defined or not.""" if not o._changed() and not o.default(): return True if o == o.default(): return True return False
Iterates over values of a given column.
def Column(self, column_name): """Iterates over values of a given column. Args: column_name: A nome of the column to retrieve the values for. Yields: Values of the specified column. Raises: KeyError: If given column is not present in the table. """ column_idx = None for ...