INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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...
def _ParseIndex(self, preread, precompile): """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 ...
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 in the index file. # pylint: disable=E110...
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: disable=E1102 fin...
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 templates. Args: index_file: String, file where template/command mappings reside. Raises: CliTableError: A template column was not found in the table. """ self.index_file = index_file or sel...
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: template_files.append(open(os.path.join(self.template_di...
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...
def ParseCmd(self, cmd_input, attributes=None, templates=None): """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, Devic...
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. ...
def AddKeys(self, key_list): """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 bet...
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) return sorted_list
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: row = self.row # If no su...
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_terminator=alt_prompt_terminator,...
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() # Clear the read buffer time.sleep(0.3 * self.global_delay_fac...
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_channel(command) time.sleep(1 * delay...
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, strip_prompt=False, strip_co...
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' 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 """ for device_type, auto...
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...
def _send_command(self, cmd=""): """ 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 -...
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 ------- ...
def _send_command_wrapper(self, cmd): """ 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 afte...
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...
def _autodetect_std(self, cmd="", search_patterns=None, re_flags=re.I, priority=99): """ 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 so...
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_type: " "currently supported platforms are: {}".format(platforms_str) ...
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 used with terminal_server device_type when you need to redispatch after interacting with terminal server. """ new_class = ssh_dispatcher(device_type) obj.device_type = de...
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 = kwargs["ssh_conn"].device_type if device_type not in scp_platforms: raise Value...
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): """ 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_requ...
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.set_terminal_width(command="terminal width 511") # Clear t...
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() command = self.normalize_cmd(command) log....
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)
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() output += self.send_command(cmd) output += self.exit_config_...
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. """ return super(RadETXBase, self).check_config_mode( check_string=check_string, pattern=pattern ...
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_RETURN = self.RETURN return super(RadETXTelnet, self).telnet_login( ...
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 )
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.""" return super(VyOSSSH, self...
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): """ 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 c...
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 chars in config mode """ return super(CiscoBaseConnection, self).check_config_mode( check_string=check_...
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 in config mode """ if not pattern: pattern = re.escape(self.base_prompt[:16]) return super...
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 mode to auto-detect the file-system.") output = self.send_command_ex...
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_or_pattern( pattern=p...
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 _timeout_exceeded(self, start, msg="Timeout exceeded!"): """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 ms...
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): """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) ...
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_data: data to be written to the channel :type out_data: str (can be either unicode/byte string) """ if self.protocol == "ssh": self.remote_conn.sendall(w...
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_data: data to be written to the channel :type out_data: str (can be either unicode/byte string) """ self._lock_netmiko_session() try: self._write_...
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 if self.protocol == "telnet": try: ...
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(): outbuf = self.remote_conn.recv(MAX_BUFFER) ...
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: # Always unlock the SSH channel, even on exception. se...
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...
def _read_channel_expect(self, pattern="", re_flags=0, max_loops=150): """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_B...
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...
def _read_channel_timing(self, delay_factor=1, max_loops=150): """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_f...
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 ...
def read_until_prompt_or_pattern(self, pattern="", re_flags=0): """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 t...
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...
def telnet_login( self, pri_prompt_terminator=r"#\s*$", alt_prompt_terminator=r">\s*$", username_pattern=r"(?:user:|username|login|user name)", pwd_pattern=r"assword", delay_factor=1, max_loops=20, ): """Telnet login. Can be username/password or just p...
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: Dictionary of SSH connection parameters :type dict_arg: dict """ connect_dict = dict_arg.copy() # Use SSHConfig to generate source content. ...
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.password, "look_for_keys": self.use_keys, ...
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_prompt=False ): """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:...
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 ...
def establish_connection(self, width=None, height=None): """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. ...
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_pre.load_system_host_keys() if ...
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): """ 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 ...
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...
def set_terminal_width(self, command="", delay_factor=1): """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. :...
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...
def set_base_prompt( self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1 ): """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 d...
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_factor :type delay_factor: int """ delay_factor = self.select_delay_factor(delay_factor) self.clear_buffer() self.wr...
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). ...
def send_command_timing( self, command_string, delay_factor=1, max_loops=150, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, ): """Execute command_string on the SSH channel using a delay-based mechanism. Generally ...
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 """ response_list = a_string.split(self.RESPONSE_RETURN) last_line = response_list[-1] if self.base_prompt in l...
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...
def _first_line_handler(self, data, search_pattern): """ 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 pote...
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...
def send_command( self, command_string, expect_string=None, delay_factor=1, max_loops=500, auto_find_prompt=True, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, ): """Execute command_string on the SSH ...
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...
def strip_command(self, command_string, output): """ 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 ...
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_string: A string that may have non-normalized line feeds i.e. output returned from device, or a device prompt :type a_string: str """ newline = re.compile("(\r\r\r\n|\r\r\n|...
Normalize CLI commands to have a single trailing newline. :param command: Command that may require line feed to be normalized :type command: str
def normalize_cmd(self, command): """Normalize CLI commands to have a single trailing newline. :param command: Command that may require line feed to be normalized :type command: str """ command = command.rstrip() command += self.RETURN return command
Check if in enable mode. Return boolean. :param check_string: Identification of privilege mode from device :type check_string: str
def check_enable_mode(self, check_string=""): """Check if in enable mode. Return boolean. :param check_string: Identification of privilege mode from device :type check_string: str """ self.write_channel(self.RETURN) output = self.read_until_prompt() return check_...
Enter enable mode. :param cmd: Device command to enter enable mode :type cmd: str :param pattern: pattern to search for indicating device is waiting for password :type pattern: str :param re_flags: Regular expression flags used in conjunction with pattern :type re_flag...
def enable(self, cmd="", pattern="ssword", re_flags=re.IGNORECASE): """Enter enable mode. :param cmd: Device command to enter enable mode :type cmd: str :param pattern: pattern to search for indicating device is waiting for password :type pattern: str :param re_flags: ...
Exit enable mode. :param exit_command: Command that exits the session from privileged mode :type exit_command: str
def exit_enable_mode(self, exit_command=""): """Exit enable mode. :param exit_command: Command that exits the session from privileged mode :type exit_command: str """ output = "" if self.check_enable_mode(): self.write_channel(self.normalize_cmd(exit_command)...
Checks if the device is in configuration mode or not. :param check_string: Identification of configuration mode from the device :type check_string: str :param pattern: Pattern to terminate reading of channel :type pattern: str
def check_config_mode(self, check_string="", pattern=""): """Checks if the device is in configuration mode or not. :param check_string: Identification of configuration mode from the device :type check_string: str :param pattern: Pattern to terminate reading of channel :type pat...
Enter into config_mode. :param config_command: Configuration command to send to the device :type config_command: str :param pattern: Pattern to terminate reading of channel :type pattern: str
def config_mode(self, config_command="", pattern=""): """Enter into config_mode. :param config_command: Configuration command to send to the device :type config_command: str :param pattern: Pattern to terminate reading of channel :type pattern: str """ output = ...
Exit from configuration mode. :param exit_config: Command to exit configuration mode :type exit_config: str :param pattern: Pattern to terminate reading of channel :type pattern: str
def exit_config_mode(self, exit_config="", pattern=""): """Exit from configuration mode. :param exit_config: Command to exit configuration mode :type exit_config: str :param pattern: Pattern to terminate reading of channel :type pattern: str """ output = "" ...
Send configuration commands down the SSH channel from a file. The file is processed line-by-line and each command is sent down the SSH channel. **kwargs are passed to send_config_set method. :param config_file: Path to configuration file to be sent to the device :type config_f...
def send_config_from_file(self, config_file=None, **kwargs): """ Send configuration commands down the SSH channel from a file. The file is processed line-by-line and each command is sent down the SSH channel. **kwargs are passed to send_config_set method. :param config...
Send configuration commands down the SSH channel. config_commands is an iterable containing all of the configuration commands. The commands will be executed one after the other. Automatically exits/enters configuration mode. :param config_commands: Multiple configuration commands to b...
def send_config_set( self, config_commands=None, exit_config_mode=True, delay_factor=1, max_loops=150, strip_prompt=False, strip_command=False, config_mode_command=None, ): """ Send configuration commands down the SSH channel. ...
Remove any ANSI (VT100) ESC codes from the output http://en.wikipedia.org/wiki/ANSI_escape_code Note: this does not capture ALL possible ANSI Escape Codes only the ones I have encountered Current codes that are filtered: ESC = '\x1b' or chr(27) ESC = is the escape char...
def strip_ansi_escape_codes(self, string_buffer): """ Remove any ANSI (VT100) ESC codes from the output http://en.wikipedia.org/wiki/ANSI_escape_code Note: this does not capture ALL possible ANSI Escape Codes only the ones I have encountered Current codes that are filt...
Try to gracefully close the SSH connection.
def disconnect(self): """Try to gracefully close the SSH connection.""" try: self.cleanup() if self.protocol == "ssh": self.paramiko_cleanup() elif self.protocol == "telnet": self.remote_conn.close() elif self.protocol == "s...
Open the session_log file.
def open_session_log(self, filename, mode="write"): """Open the session_log file.""" if mode == "append": self.session_log = open(filename, mode="ab") else: self.session_log = open(filename, mode="wb") self._session_log_close = True
Close the session_log file (if it is a file that we opened).
def close_session_log(self): """Close the session_log file (if it is a file that we opened).""" if self.session_log is not None and self._session_log_close: self.session_log.close() self.session_log = None
Saves Config Using write command
def save_config(self, cmd="write", confirm=False, confirm_response=""): """Saves Config Using write command""" return super(IpInfusionOcNOSBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
For all telnet options, re-implement the default telnetlib behaviour and refuse to handle any options. If the server expresses interest in 'terminal type' option, then reply back with 'xterm' terminal type.
def _process_option(self, tsocket, command, option): """ For all telnet options, re-implement the default telnetlib behaviour and refuse to handle any options. If the server expresses interest in 'terminal type' option, then reply back with 'xterm' terminal type. """ if c...
Disable paging is only available with specific roles so it may fail.
def disable_paging(self, delay_factor=1): """Disable paging is only available with specific roles so it may fail.""" check_command = "get system status | grep Virtual" output = self.send_command_timing(check_command) self.allow_disable_global = True self.vdoms = False sel...
Save the state of the output mode so it can be reset at the end of the session.
def _retrieve_output_mode(self): """Save the state of the output mode so it can be reset at the end of the session.""" reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n") output = self.send_command("get system console") result_mode_re = reg_mode.search(output) if result_mode...
Re-enable paging globally.
def cleanup(self): """Re-enable paging globally.""" if self.allow_disable_global: # Return paging state output_mode_cmd = "set output {}".format(self._output_mode) enable_paging_commands = ["config system console", output_mode_cmd, "end"] if self.vdoms: ...
Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output.
def set_base_prompt( self, pri_prompt_terminator=":", alt_prompt_terminator="#", delay_factor=2 ): """Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output.""" super(AccedianSSH, self).set_base_prompt( pri_prompt_terminator=pri_prompt_terminator, ...
Prepare the session after the connection has been established. Procurve uses - 'Press any key to continue'
def session_preparation(self): """ Prepare the session after the connection has been established. Procurve uses - 'Press any key to continue' """ delay_factor = self.select_delay_factor(delay_factor=0) output = "" count = 1 while count <= 30: o...
Enter enable mode
def enable( self, cmd="enable", pattern="password", re_flags=re.IGNORECASE, default_username="manager", ): """Enter enable mode""" if self.check_enable_mode(): return "" output = self.send_command_timing(cmd) if ( "usern...
Gracefully exit the SSH session.
def cleanup(self): """Gracefully exit the SSH session.""" self.exit_config_mode() self.write_channel("logout" + self.RETURN) count = 0 while count <= 5: time.sleep(0.5) output = self.read_channel() if "Do you want to log out" in output: ...
Save Config.
def save_config(self, cmd="write memory", confirm=False, confirm_response=""): """Save Config.""" return super(HPProcurveBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Telnet login: can be username/password or just password.
def telnet_login( self, pri_prompt_terminator="#", alt_prompt_terminator=">", username_pattern=r"Login Name:", pwd_pattern=r"assword", delay_factor=1, max_loops=60, ): """Telnet login: can be username/password or just password.""" super(HPProcu...
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() self.tmsh_mode() self.set_base_prompt() self.disable_paging( command="modify cli preference pager disabled disp...
tmsh command is equivalent to config command on F5.
def tmsh_mode(self, delay_factor=1): """tmsh command is equivalent to config command on F5.""" delay_factor = self.select_delay_factor(delay_factor) self.clear_buffer() command = "{}tmsh{}".format(self.RETURN, self.RETURN) self.write_channel(command) time.sleep(1 * delay_...
Determine base prompt.
def set_base_prompt( self, pri_prompt_terminator="$", alt_prompt_terminator="#", delay_factor=1 ): """Determine base prompt.""" return super(LinuxSSH, self).set_base_prompt( pri_prompt_terminator=pri_prompt_terminator, alt_prompt_terminator=alt_prompt_terminator, ...