text
stringlengths
81
112k
Try to send an SNMP GET operation using SNMPv2 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value from the OID you are trying to retrieve. def _g...
Wrapper for generic SNMP call. def _get_snmp(self, oid): """Wrapper for generic SNMP call.""" if self.snmp_version in ["v1", "v2c"]: return self._get_snmpv2c(oid) else: return self._get_snmpv3(oid)
Try to guess the device_type using SNMP GET based on the SNMP_MAPPER dict. The type which is returned is directly matching the name in *netmiko.ssh_dispatcher.CLASS_MAPPER_BASE* dict. Thus you can use this name to retrieve automatically the right ConnectionClass Returns -------...
Check if at shell prompt root@ and go into CLI. def enter_cli_mode(self): """Check if at shell prompt root@ and go into CLI.""" delay_factor = self.select_delay_factor(delay_factor=0) count = 0 cur_prompt = "" while count < 50: self.write_channel(self.RETURN) ...
Exit configuration mode. def exit_config_mode(self, exit_config="exit configuration-mode"): """Exit configuration mode.""" output = "" if self.check_config_mode(): output = self.send_command_timing( exit_config, strip_prompt=False, strip_command=False ) ...
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. Automatically enters configuration mode default: command_string = commit check and (confirm or confirm_dely or comment): Exc...
Strip the trailing router prompt from the output. def strip_prompt(self, *args, **kwargs): """Strip the trailing router prompt from the output.""" a_string = super(FlexvnfSSH, self).strip_prompt(*args, **kwargs) return self.strip_context_items(a_string)
Enter enable mode. With RADIUS can prompt for User Name SSH@Lab-ICX7250>en User Name:service_netmiko Password: SSH@Lab-ICX7250# def enable( self, cmd="enable", pattern=r"(ssword|User Name)", re_flags=re.IGNORECASE ): """Enter enable mode. With RADIUS ...
Saves configuration. def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Saves configuration.""" return super(RuckusFastironBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Ruckus FastIron/ICX does not always echo commands to output by default. If server expresses interest in 'ECHO' option, then reply back with 'DO ECHO' def _process_option(self, tsocket, command, option): """ Ruckus FastIron/ICX does not always echo commands to output by default. ...
Use Netmiko to execute show version. Use a queue to pass the data back to the main process. def show_version_queue(a_device, output_q): """ Use Netmiko to execute show version. Use a queue to pass the data back to the main process. """ output_dict = {} remote_conn = ConnectHandler(**a_devic...
Use processes and Netmiko to connect to each of the devices. Execute 'show version' on each device. Use a queue to pass the output back to the parent process. Record the amount of time required to do this. def main(): """ Use processes and Netmiko to connect to each of the devices. Execute 'show ve...
Prepare the session after the connection has been established. def session_preparation(self): """Prepare the session after the connection has been established.""" self._test_channel_read() self.set_base_prompt() if self.secret: self.enable() else: self.as...
If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change. def send_command_timing(self, *args, **kwargs): """ If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change. """ outpu...
If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change. def send_command(self, *args, **kwargs): """ If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change. """ if len(args)...
Cisco ASA in multi-context mode needs to have the base prompt updated (if you switch contexts i.e. 'changeto') This switch of ASA contexts can occur in configuration mode. If this happens the trailing '(config*' needs stripped off. def set_base_prompt(self, *args, **kwargs): """ ...
Handle ASA reaching privilege level 15 using login twb-dc-fw1> login Username: admin Password: ************ def asa_login(self): """ Handle ASA reaching privilege level 15 using login twb-dc-fw1> login Username: admin Password: ************ """ ...
Saves Config def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Saves Config""" return super(CiscoAsaSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
IOS-XR requires you not exit from configuration mode. def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """IOS-XR requires you not exit from configuration mode.""" return super(CiscoXrSSH, self).send_config_set( config_commands=config_commands, exit_config_mo...
Commit the candidate configuration. default (no options): command_string = commit confirm and confirm_delay: command_string = commit confirmed <confirm_delay> label (which is a label name): command_string = commit label <label> comment: co...
Checks if the device is in configuration mode or not. IOS-XR, unfortunately, does this: RP/0/RSP0/CPU0:BNG(admin)# def check_config_mode(self, check_string=")#", pattern=r"[#\$]"): """Checks if the device is in configuration mode or not. IOS-XR, unfortunately, does this: RP/0/...
IOS-XR defaults with timestamps enabled # show md5 file /bootflash:/boot/grub/grub.cfg Sat Mar 3 17:49:03.596 UTC c84843f0030efd44b01343fdb8c2e801 def process_md5(self, md5_output, pattern=r"^([a-fA-F0-9]+)$"): """ IOS-XR defaults with timestamps enabled # show md5 fi...
Saves Config def save_config( self, cmd="copy running-configuration startup-configuration", confirm=False, confirm_response="", ): """Saves Config""" return super(DellOS10SSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response ...
Get the file size of the remote file. def remote_file_size(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" if remote_file is None: if self.direction == "put": remote_file = self.dest_file elif self.direction == "get": ...
Return space available on remote device. def remote_space_available(self, search_pattern=r"(\d+) bytes free"): """Return space available on remote device.""" remote_cmd = 'system "df {}"'.format(self.folder_name) remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd) for line...
Check if the dest_file already exists on the file system (return boolean). def check_file_exists(self, remote_cmd="dir home"): """Check if the dest_file already exists on the file system (return boolean).""" if self.direction == "put": remote_out = self.ssh_ctl_chan.send_command_expect(remo...
SCP copy the file from the remote device to local system. def get_file(self): """SCP copy the file from the remote device to local system.""" source_file = "{}".format(self.source_file) self.scp_conn.scp_get_file(source_file, self.dest_file) self.scp_conn.close()
Save config: write mem def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Save config: write mem""" return super(OneaccessOneOSBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Reads index file and stores entries in TextTable. For optimisation reasons, a second table is created with compiled entries. Args: preread: func, Pre-processing, applied to each field as it is read. precompile: func, Pre-compilation, applied to each field before compiling. Raises: IndexTab...
Returns the row number that matches the supplied attributes. def GetRowMatch(self, attributes): """Returns the row number that matches the supplied attributes.""" for row in self.compiled: try: for key in attributes: # Silently skip attributes not present...
Synchronisation decorator. def synchronised(func): """Synchronisation decorator.""" # pylint: disable=E0213 def Wrapper(main_obj, *args, **kwargs): main_obj._lock.acquire() # pylint: disable=W0212 try: return func(main_obj, *args, **kwargs) # pylint: d...
Reads the IndexTable index file of commands and templates. Args: index_file: String, file where template/command mappings reside. Raises: CliTableError: A template column was not found in the table. def ReadIndex(self, index_file=None): """Reads the IndexTable index file of commands and tem...
Parses a string of templates into a list of file handles. def _TemplateNamesToFiles(self, template_str): """Parses a string of templates into a list of file handles.""" template_list = template_str.split(":") template_files = [] try: for tmplt in template_list: ...
Creates a TextTable table of values from cmd_input string. Parses command output with template/s. If more than one template is found subsequent tables are merged if keys match (dropped otherwise). Args: cmd_input: String, Device/command response. attributes: Dict, attribute that further refine m...
Executed against each field of each row read from index table. def _PreParse(self, key, value): """Executed against each field of each row read from index table.""" if key == "Command": return re.sub(r"(\[\[.+?\]\])", self._Completion, value) else: return value
Return LabelValue with FSM derived keys. def LabelValueTable(self, keys=None): """Return LabelValue with FSM derived keys.""" keys = keys or self.superkey # pylint: disable=E1002 return super(CliTable, self).LabelValueTable(keys)
Overrides sort func to use the KeyValue for the key. def sort(self, cmp=None, key=None, reverse=False): """Overrides sort func to use the KeyValue for the key.""" if not key and self._keys: key = self.KeyValue super(CliTable, self).sort(cmp=cmp, key=key, reverse=reverse)
Mark additional columns as being part of the superkey. Supplements the Keys already extracted from the FSM template. Useful when adding new columns to existing tables. Note: This will impact attempts to further 'extend' the table as the superkey must be common between tables for successful extension. ...
Returns a set of column names that together constitute the superkey. def superkey(self): """Returns a set of column names that together constitute the superkey.""" sorted_list = [] for header in self.header: if header in self._keys: sorted_list.append(header) ...
Returns the super key value for the row. def KeyValue(self, row=None): """Returns the super key value for the row.""" if not row: if self._iterator: # If we are inside an iterator use current row iteration. row = self[self._iterator] else: ...
Determine base prompt. def set_base_prompt( self, pri_prompt_terminator="$", alt_prompt_terminator="#", delay_factor=1 ): """Determine base prompt.""" return super(DellIsilonSSH, self).set_base_prompt( pri_prompt_terminator=pri_prompt_terminator, alt_prompt_terminato...
Remove Null code def strip_ansi_escape_codes(self, string_buffer): """Remove Null code""" output = re.sub(r"\x00", "", string_buffer) return super(DellIsilonSSH, self).strip_ansi_escape_codes(output)
Prepare the session after the connection has been established. def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self.zsh_mode() self.find_prompt(delay_factor=1) self.set_base_prompt() # Clea...
Run zsh command to unify the environment def zsh_mode(self, delay_factor=1, prompt_terminator="$"): """Run zsh command to unify the environment""" delay_factor = self.select_delay_factor(delay_factor) self.clear_buffer() command = self.RETURN + "zsh" + self.RETURN self.write_cha...
Attempt to become root. def config_mode(self, config_command="sudo su"): """Attempt to become root.""" delay_factor = self.select_delay_factor(delay_factor=1) output = "" if not self.check_config_mode(): output += self.send_command_timing( config_command, str...
Disable paging def disable_paging(self, command="no pager", delay_factor=1): """Disable paging""" return super(QuantaMeshSSH, self).disable_paging(command=command)
Saves Config def save_config( self, cmd="copy running-config startup-config", confirm=False, confirm_response="", ): """Saves Config""" return super(QuantaMeshSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE Returns ------- best_match : str or None The device type that is currently the best to use to interact with the device def autodetect(self): """ Try to guess the best 'device_type' base...
Handle reading/writing channel directly. It is also sanitizing the output received. Parameters ---------- cmd : str, optional The command to send to the remote device (default : "", just send a new line) Returns ------- output : str The output fr...
Send command to the remote device with a caching feature to avoid sending the same command twice based on the SSH_MAPPER_BASE dict cmd key. Parameters ---------- cmd : str The command to send to the remote device after checking cache. Returns ------- ...
Standard method to try to auto-detect the device type. This method will be called for each device_type present in SSH_MAPPER_BASE dict ('dispatch' key). It will attempt to send a command and match some regular expression from the ouput for each entry in SSH_MAPPER_BASE ('cmd' and 'search_pattern...
Save Config def save_config( self, cmd="write memory flash-synchro", confirm=False, confirm_response="" ): """Save Config""" return super(AlcatelAosSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Factory function selects the proper class and creates object based on device_type. def ConnectHandler(*args, **kwargs): """Factory function selects the proper class and creates object based on device_type.""" if kwargs["device_type"] not in platforms: raise ValueError( "Unsupported device_t...
Dynamically change Netmiko object's class to proper class. Generally used with terminal_server device_type when you need to redispatch after interacting with terminal server. def redispatch(obj, device_type, session_prep=True): """Dynamically change Netmiko object's class to proper class. Generally u...
Factory function selects the proper SCP class and creates object based on device_type. def FileTransfer(*args, **kwargs): """Factory function selects the proper SCP class and creates object based on device_type.""" if len(args) >= 1: device_type = args[0].device_type else: device_type = kwa...
This pattern was modeled on a method from the Python Packaging User Guide: https://packaging.python.org/en/latest/single_source_version.html We read instead of importing so we don't get import errors if our code imports from dependencies listed in install_requires. def find_version(*file_paths): "...
Prepare the session after the connection has been established. def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self._test_channel_read() self.set_base_prompt() self.disable_paging() self.se...
Checks if the device is in configuration mode def check_config_mode(self, check_string=")#", pattern=""): """Checks if the device is in configuration mode""" return super(CalixB6Base, self).check_config_mode(check_string=check_string)
Disable paging default to a Cisco CLI method. def disable_paging(self, command="terminal length 999", delay_factor=1): """Disable paging default to a Cisco CLI method.""" delay_factor = self.select_delay_factor(delay_factor) time.sleep(delay_factor * 0.1) self.clear_buffer() com...
Save Config on Mellanox devices Enters and Leaves Config Mode def save_config( self, cmd="configuration write", confirm=False, confirm_response="" ): """Save Config on Mellanox devices Enters and Leaves Config Mode""" output = self.enable() output += self.config_mode() outpu...
Enter into configuration mode on remote device. def config_mode(self, config_command="config", pattern=">config"): """Enter into configuration mode on remote device.""" return super(RadETXBase, self).config_mode( config_command=config_command, pattern=pattern )
Checks if the device is in configuration mode or not. Rad config starts with baseprompt>config. def check_config_mode(self, check_string=">config", pattern=""): """ Checks if the device is in configuration mode or not. Rad config starts with baseprompt>config. """ retu...
Exit from configuration mode. def exit_config_mode(self, exit_config="exit all", pattern="#"): """Exit from configuration mode.""" return super(RadETXBase, self).exit_config_mode( exit_config=exit_config, pattern=pattern )
RAD presents with the following on login user> password> **** def telnet_login( self, username_pattern=r"(?:user>)", alt_prompt_term=r"#\s*$", **kwargs ): """ RAD presents with the following on login user> password> **** """ self.TELNET_RE...
Enter configuration mode. def config_mode(self, config_command="configure", pattern=r"[edit]"): """Enter configuration mode.""" return super(VyOSSSH, self).config_mode( config_command=config_command, pattern=pattern )
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. default: command_string = commit comment: command_string = commit comment <comment> def commit(self, comment="", delay_factor=0.1): ...
Remain in configuration mode. def send_config_set( self, config_commands=None, exit_config_mode=False, delay_factor=1, max_loops=150, strip_prompt=False, strip_command=False, config_mode_command=None, ): """Remain in configuration mode.""" ...
Checks if the device is in configuration mode or not. Cisco IOS devices abbreviate the prompt at 20 chars in config mode def check_config_mode(self, check_string=")#", pattern=""): """ Checks if the device is in configuration mode or not. Cisco IOS devices abbreviate the prompt at 20 ...
Enter into configuration mode on remote device. Cisco IOS devices abbreviate the prompt at 20 chars in config mode def config_mode(self, config_command="config term", pattern=""): """ Enter into configuration mode on remote device. Cisco IOS devices abbreviate the prompt at 20 chars i...
Exit from configuration mode. def exit_config_mode(self, exit_config="end", pattern="#"): """Exit from configuration mode.""" return super(CiscoBaseConnection, self).exit_config_mode( exit_config=exit_config, pattern=pattern )
Autodetect the file system on the remote device. Used by SCP operations. def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"): """Autodetect the file system on the remote device. Used by SCP operations.""" if not self.check_enable_mode(): raise ValueError("Must be in enable mo...
Enable mode on MRV uses no password. def enable(self, cmd="enable", pattern=r"#", re_flags=re.IGNORECASE): """Enable mode on MRV uses no password.""" output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) output += self.read_until_prompt...
Saves configuration. def save_config(self, cmd="save config flash", confirm=False, confirm_response=""): """Saves configuration.""" return super(MrvOptiswitchSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Prepare the session after the connection has been established. def session_preparation(self): """Prepare the session after the connection has been established.""" self.set_base_prompt() cmd = self.RETURN + "rows 0" + self.RETURN self.disable_paging(command=cmd)
Raise NetMikoTimeoutException if waiting too much in the serving queue. :param start: Initial start time to see if session lock timeout has been exceeded :type start: float (from time.time() call i.e. epoch time) :param msg: Exception message if timeout was exceeded :type msg: str def...
Try to acquire the Netmiko session lock. If not available, wait in the queue until the channel is available again. :param start: Initial start time to measure the session timeout :type start: float (from time.time() call i.e. epoch time) def _lock_netmiko_session(self, start=None): """...
Generic handler that will write to both SSH and telnet channel. :param out_data: data to be written to the channel :type out_data: str (can be either unicode/byte string) def _write_channel(self, out_data): """Generic handler that will write to both SSH and telnet channel. :param out_...
Generic handler that will write to both SSH and telnet channel. :param out_data: data to be written to the channel :type out_data: str (can be either unicode/byte string) def write_channel(self, out_data): """Generic handler that will write to both SSH and telnet channel. :param out_d...
Returns a boolean flag with the state of the connection. def is_alive(self): """Returns a boolean flag with the state of the connection.""" null = chr(0) if self.remote_conn is None: log.error("Connection is not initialised, is_alive returns False") return False ...
Generic handler that will read all the data from an SSH or telnet channel. def _read_channel(self): """Generic handler that will read all the data from an SSH or telnet channel.""" if self.protocol == "ssh": output = "" while True: if self.remote_conn.recv_ready(...
Generic handler that will read all the data from an SSH or telnet channel. def read_channel(self): """Generic handler that will read all the data from an SSH or telnet channel.""" output = "" self._lock_netmiko_session() try: output = self._read_channel() finally: ...
Function that reads channel until pattern is detected. pattern takes a regular expression. By default pattern will be self.base_prompt Note: this currently reads beyond pattern. In the case of SSH it reads MAX_BUFFER. In the case of telnet it reads all non-blocking data. Ther...
Read data on the channel based on timing delays. Attempt to read channel max_loops number of times. If no data this will cause a 15 second delay. Once data is encountered read channel for another two seconds (2 * delay_factor) to make sure reading of channel is complete. :para...
Read until either self.base_prompt or pattern is detected. :param pattern: the pattern used to identify that the output is complete (i.e. stop \ reading when pattern is detected). pattern will be combined with self.base_prompt to \ terminate output reading when the first of self.base_prompt or ...
Telnet login. Can be username/password or just password. :param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt :type pri_prompt_terminator: str :param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt :type alt_prompt...
Update SSH connection parameters based on contents of SSH 'config' file. :param dict_arg: Dictionary of SSH connection parameters :type dict_arg: dict def _use_ssh_config(self, dict_arg): """Update SSH connection parameters based on contents of SSH 'config' file. :param dict_arg: Dict...
Generate dictionary of Paramiko connection parameters. def _connect_params_dict(self): """Generate dictionary of Paramiko connection parameters.""" conn_dict = { "hostname": self.host, "port": self.port, "username": self.username, "password": self.passwor...
Strip out command echo, trailing router prompt and ANSI escape codes. :param output: Output from a remote network device :type output: unicode string :param strip_command: :type strip_command: def _sanitize_output( self, output, strip_command=False, command_string=None, strip_...
Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException width and height are needed for Fortinet paging setting. :param width: Specified width of the VT100 terminal window ...
Prepare for Paramiko SSH connection. def _build_ssh_client(self): """Prepare for Paramiko SSH connection.""" # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Load host_keys for better SSH security if self.system_host_keys: remote_conn_p...
Choose the greater of delay_factor or self.global_delay_factor (default). In fast_cli choose the lesser of delay_factor of self.global_delay_factor. :param delay_factor: See __init__: global_delay_factor :type delay_factor: int def select_delay_factor(self, delay_factor): """ C...
CLI terminals try to automatically adjust the line based on the width of the terminal. This causes the output to get distorted when accessed programmatically. Set terminal width to 511 which works on a broad set of devices. :param command: Command string to send to the device :type com...
Sets self.base_prompt Used as delimiter for stripping of trailing prompt in output. Should be set to something that is general and applies in multiple contexts. For Cisco devices this will be set to router hostname (i.e. prompt without '>' or '#'). This will be set on entering user ex...
Finds the current network device prompt, last line only. :param delay_factor: See __init__: global_delay_factor :type delay_factor: int def find_prompt(self, delay_factor=1): """Finds the current network device prompt, last line only. :param delay_factor: See __init__: global_delay_fa...
Execute command_string on the SSH channel using a delay-based mechanism. Generally used for show commands. :param command_string: The command to be executed on the remote device. :type command_string: str :param delay_factor: Multiplying factor used to adjust delays (default: 1). ...
Strip the trailing router prompt from the output. :param a_string: Returned string from device :type a_string: str def strip_prompt(self, a_string): """Strip the trailing router prompt from the output. :param a_string: Returned string from device :type a_string: str ""...
In certain situations the first line will get repainted which causes a false match on the terminating pattern. Filter this out. returns a tuple of (data, first_line_processed) Where data is the original data potentially with the first line modified and the first_line_processed...
Execute command_string on the SSH channel using a pattern-based mechanism. Generally used for show commands. By default this method will keep waiting to receive data until the network device prompt is detected. The current network device prompt will be determined automatically. :param c...
Strip command_string from output string Cisco IOS adds backspaces into output for long commands (i.e. for commands that line wrap) :param command_string: The command string sent to the device :type command_string: str :param output: The returned output as a result of the command strin...
Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str def normalize_linefeeds(self, a_string): """Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` :param a...