text_prompt
stringlengths
100
17.7k
code_prompt
stringlengths
7
9.86k
<SYSTEM_TASK:> Calculates the frequency of at most nbits logical zeros and returns the mean of these frequencies <END_TASK> <USER_TASK:> Description: def estimate_frequency_for_zero(self, sample_rate: float, nbits=42) -> float: """ Calculates the frequency of at most nbits logical zeros and returns the mean of these frequencies :param nbits: :return: """
return self.__estimate_frequency_for_bit(False, sample_rate, nbits)
<SYSTEM_TASK:> Return the most frequent value in list. <END_TASK> <USER_TASK:> Description: def get_most_frequent_value(values: list): """ Return the most frequent value in list. If there is no unique one, return the maximum of the most frequent values :param values: :return: """
if len(values) == 0: return None most_common = Counter(values).most_common() result, max_count = most_common[0] for value, count in most_common: if count < max_count: return result else: result = value return result
<SYSTEM_TASK:> Get the list of start, end indices of messages <END_TASK> <USER_TASK:> Description: def segment_messages_from_magnitudes(magnitudes: np.ndarray, noise_threshold: float): """ Get the list of start, end indices of messages :param magnitudes: Magnitudes of samples :param noise_threshold: Threshold for noise :return: """
return c_auto_interpretation.segment_messages_from_magnitudes(magnitudes, noise_threshold)
<SYSTEM_TASK:> returns a string of new device messages separated by newlines <END_TASK> <USER_TASK:> Description: def read_messages(self) -> str: """ returns a string of new device messages separated by newlines :return: """
if self.backend == Backends.grc: errors = self.__dev.read_errors() if "FATAL: " in errors: self.fatal_error_occurred.emit(errors[errors.index("FATAL: "):]) return errors elif self.backend == Backends.native: messages = "\n".join(self.__dev.device_messages) self.__dev.device_messages.clear() if messages and not messages.endswith("\n"): messages += "\n" if "successfully started" in messages: self.ready_for_action.emit() elif "failed to start" in messages: self.fatal_error_occurred.emit(messages[messages.index("failed to start"):]) return messages elif self.backend == Backends.network: return "" else: raise ValueError("Unsupported Backend")
<SYSTEM_TASK:> Convenience function for creating a ready-to-go CloudflareScraper object. <END_TASK> <USER_TASK:> Description: def create_scraper(cls, sess=None, **kwargs): """ Convenience function for creating a ready-to-go CloudflareScraper object. """
scraper = cls(**kwargs) if sess: attrs = ["auth", "cert", "cookies", "headers", "hooks", "params", "proxies", "data"] for attr in attrs: val = getattr(sess, attr, None) if val: setattr(scraper, attr, val) return scraper
<SYSTEM_TASK:> Adding a delay after login. <END_TASK> <USER_TASK:> Description: def special_login_handler(self, delay_factor=1): """Adding a delay after login."""
delay_factor = self.select_delay_factor(delay_factor) self.write_channel(self.RETURN) time.sleep(1 * delay_factor)
<SYSTEM_TASK:> Use threads and Netmiko to connect to each of the devices. Execute <END_TASK> <USER_TASK:> Description: def main(): """ Use threads and Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this. """
start_time = datetime.now() for a_device in devices: my_thread = threading.Thread(target=show_version, args=(a_device,)) my_thread.start() main_thread = threading.currentThread() for some_thread in threading.enumerate(): if some_thread != main_thread: print(some_thread) some_thread.join() print("\nElapsed time: " + str(datetime.now() - start_time))
<SYSTEM_TASK:> Establish the secure copy connection. <END_TASK> <USER_TASK:> Description: def establish_scp_conn(self): """Establish the secure copy connection."""
ssh_connect_params = self.ssh_ctl_chan._connect_params_dict() self.scp_conn = self.ssh_ctl_chan._build_ssh_client() self.scp_conn.connect(**ssh_connect_params) self.scp_client = scp.SCPClient(self.scp_conn.get_transport())
<SYSTEM_TASK:> Compare md5 of file on network device to md5 of local file. <END_TASK> <USER_TASK:> Description: def compare_md5(self): """Compare md5 of file on network device to md5 of local file."""
if self.direction == "put": remote_md5 = self.remote_md5() return self.source_md5 == remote_md5 elif self.direction == "get": local_md5 = self.file_md5(self.dest_file) return self.source_md5 == local_md5
<SYSTEM_TASK:> SCP copy the file from the local system to the remote device. <END_TASK> <USER_TASK:> Description: def put_file(self): """SCP copy the file from the local system to the remote device."""
destination = "{}/{}".format(self.file_system, self.dest_file) self.scp_conn.scp_transfer_file(self.source_file, destination) # Must close the SCP connection to get the file written (flush) self.scp_conn.close()
<SYSTEM_TASK:> Enable SCP on remote device. <END_TASK> <USER_TASK:> Description: def enable_scp(self, cmd=None): """ Enable SCP on remote device. Defaults to Cisco IOS command """
if cmd is None: cmd = ["ip scp server enable"] elif not hasattr(cmd, "__iter__"): cmd = [cmd] self.ssh_ctl_chan.send_config_set(cmd)
<SYSTEM_TASK:> Disable SCP on remote device. <END_TASK> <USER_TASK:> Description: def disable_scp(self, cmd=None): """ Disable SCP on remote device. Defaults to Cisco IOS command """
if cmd is None: cmd = ["no ip scp server enable"] elif not hasattr(cmd, "__iter__"): cmd = [cmd] self.ssh_ctl_chan.send_config_set(cmd)
<SYSTEM_TASK:> Strip command_string from output string. <END_TASK> <USER_TASK:> Description: def strip_command(self, command_string, output): """Strip command_string from output string."""
output_list = output.split(command_string) return self.RESPONSE_RETURN.join(output_list)
<SYSTEM_TASK:> Palo Alto requires an extra delay <END_TASK> <USER_TASK:> Description: def send_command(self, *args, **kwargs): """Palo Alto requires an extra delay"""
kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5) return super(PaloAltoPanosBase, self).send_command(*args, **kwargs)
<SYSTEM_TASK:> Prepare the session after the connection has been established. <END_TASK> <USER_TASK:> Description: def session_preparation(self): """ Prepare the session after the connection has been established. Extra time to read HP banners. """
delay_factor = self.select_delay_factor(delay_factor=0) i = 1 while i <= 4: # Comware can have a banner that prompts you to continue # 'Press Y or ENTER to continue, N to exit.' time.sleep(0.5 * delay_factor) self.write_channel("\n") i += 1 time.sleep(0.3 * delay_factor) self.clear_buffer() self._test_channel_read(pattern=r"[>\]]") self.set_base_prompt() command = self.RETURN + "screen-length disable" self.disable_paging(command=command) # Clear the read buffer time.sleep(0.3 * self.global_delay_factor) self.clear_buffer()
<SYSTEM_TASK:> Try to send an SNMP GET operation using SNMPv3 for the specified OID. <END_TASK> <USER_TASK:> Description: def _get_snmpv3(self, oid): """ Try to send an SNMP GET operation using SNMPv3 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. """
snmp_target = (self.hostname, self.snmp_port) cmd_gen = cmdgen.CommandGenerator() (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd( cmdgen.UsmUserData( self.user, self.auth_key, self.encrypt_key, authProtocol=self.auth_proto, privProtocol=self.encryp_proto, ), cmdgen.UdpTransportTarget(snmp_target, timeout=1.5, retries=2), oid, lookupNames=True, lookupValues=True, ) if not error_detected and snmp_data[0][1]: return text_type(snmp_data[0][1]) return ""
<SYSTEM_TASK:> Try to send an SNMP GET operation using SNMPv2 for the specified OID. <END_TASK> <USER_TASK:> Description: def _get_snmpv2c(self, oid): """ 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. """
snmp_target = (self.hostname, self.snmp_port) cmd_gen = cmdgen.CommandGenerator() (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd( cmdgen.CommunityData(self.community), cmdgen.UdpTransportTarget(snmp_target, timeout=1.5, retries=2), oid, lookupNames=True, lookupValues=True, ) if not error_detected and snmp_data[0][1]: return text_type(snmp_data[0][1]) return ""
<SYSTEM_TASK:> Use Netmiko to execute show version. Use a queue to pass the data back to <END_TASK> <USER_TASK:> Description: 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_device) hostname = remote_conn.base_prompt output = ("#" * 80) + "\n" output += remote_conn.send_command("show version") + "\n" output += ("#" * 80) + "\n" output_dict[hostname] = output output_q.put(output_dict)
<SYSTEM_TASK:> Use processes and Netmiko to connect to each of the devices. Execute <END_TASK> <USER_TASK:> Description: def main(): """ 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. """
start_time = datetime.now() output_q = Queue(maxsize=20) procs = [] for a_device in devices: my_proc = Process(target=show_version_queue, args=(a_device, output_q)) my_proc.start() procs.append(my_proc) # Make sure all processes have finished for a_proc in procs: a_proc.join() while not output_q.empty(): my_dict = output_q.get() for k, val in my_dict.items(): print(k) print(val) print("\nElapsed time: " + str(datetime.now() - start_time))
<SYSTEM_TASK:> IOS-XR requires you not exit from configuration mode. <END_TASK> <USER_TASK:> Description: 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_mode=False, **kwargs )
<SYSTEM_TASK:> SCP copy the file from the remote device to local system. <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Returns the row number that matches the supplied attributes. <END_TASK> <USER_TASK:> Description: 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=E1103 if ( key in row.header and row[key] and not row[key].match(attributes[key]) ): # This line does not match, so break and try next row. raise StopIteration() return row.row except StopIteration: pass return 0
<SYSTEM_TASK:> Parses a string of templates into a list of file handles. <END_TASK> <USER_TASK:> Description: 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_dir, tmplt), "r")) except: # noqa for tmplt in template_files: tmplt.close() raise return template_files
<SYSTEM_TASK:> Overrides sort func to use the KeyValue for the key. <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Returns a set of column names that together constitute the superkey. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Returns the super key value for the row. <END_TASK> <USER_TASK:> Description: 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 superkey then use row number. if not self.superkey: return ["%s" % row.row] sorted_list = [] for header in self.header: if header in self.superkey: sorted_list.append(row[header]) return sorted_list
<SYSTEM_TASK:> Run zsh command to unify the environment <END_TASK> <USER_TASK:> Description: 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_factor) self.set_prompt() self.clear_buffer()
<SYSTEM_TASK:> Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE <END_TASK> <USER_TASK:> Description: 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, autodetect_dict in SSH_MAPPER_BASE.items(): tmp_dict = autodetect_dict.copy() call_method = tmp_dict.pop("dispatch") autodetect_method = getattr(self, call_method) accuracy = autodetect_method(**tmp_dict) if accuracy: self.potential_matches[device_type] = accuracy if accuracy >= 99: # Stop the loop as we are sure of our match best_match = sorted( self.potential_matches.items(), key=lambda t: t[1], reverse=True ) self.connection.disconnect() return best_match[0][0] if not self.potential_matches: self.connection.disconnect() return None best_match = sorted( self.potential_matches.items(), key=lambda t: t[1], reverse=True ) self.connection.disconnect() return best_match[0][0]
<SYSTEM_TASK:> Send command to the remote device with a caching feature to avoid sending the same command <END_TASK> <USER_TASK:> Description: 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 after checking cache. Returns ------- response : str The response from the remote device. """
cached_results = self._results_cache.get(cmd) if not cached_results: response = self._send_command(cmd) self._results_cache[cmd] = response return response else: return cached_results
<SYSTEM_TASK:> Factory function selects the proper class and creates object based on device_type. <END_TASK> <USER_TASK:> Description: 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) ) ConnectionClass = ssh_dispatcher(kwargs["device_type"]) return ConnectionClass(*args, **kwargs)
<SYSTEM_TASK:> Dynamically change Netmiko object's class to proper class. <END_TASK> <USER_TASK:> Description: 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 = device_type obj.__class__ = new_class if session_prep: obj._try_session_preparation()
<SYSTEM_TASK:> Factory function selects the proper SCP class and creates object based on device_type. <END_TASK> <USER_TASK:> Description: 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 ValueError( "Unsupported SCP device_type: " "currently supported platforms are: {}".format(scp_platforms_str) ) FileTransferClass = FILE_TRANSFER_MAP[device_type] return FileTransferClass(*args, **kwargs)
<SYSTEM_TASK:> Checks if the device is in configuration mode <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Save Config on Mellanox devices Enters and Leaves Config Mode <END_TASK> <USER_TASK:> Description: 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_mode() return output
<SYSTEM_TASK:> RAD presents with the following on login <END_TASK> <USER_TASK:> Description: 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( username_pattern=username_pattern, alt_prompt_terminator=alt_prompt_term, **kwargs )
<SYSTEM_TASK:> Enter configuration mode. <END_TASK> <USER_TASK:> Description: 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 )
<SYSTEM_TASK:> Remain in configuration mode. <END_TASK> <USER_TASK:> Description: 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).send_config_set( config_commands=config_commands, exit_config_mode=exit_config_mode, delay_factor=delay_factor, max_loops=max_loops, strip_prompt=strip_prompt, strip_command=strip_command, config_mode_command=config_mode_command, )
<SYSTEM_TASK:> Autodetect the file system on the remote device. Used by SCP operations. <END_TASK> <USER_TASK:> Description: 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_expect(cmd) match = re.search(pattern, output) if match: file_system = match.group(1) # Test file_system cmd = "dir {}".format(file_system) output = self.send_command_expect(cmd) if "% Invalid" in output or "%Error:" in output: raise ValueError( "An error occurred in dynamically determining remote file " "system: {} {}".format(cmd, output) ) else: return file_system raise ValueError( "An error occurred in dynamically determining remote file " "system: {} {}".format(cmd, output) )
<SYSTEM_TASK:> Raise NetMikoTimeoutException if waiting too much in the serving queue. <END_TASK> <USER_TASK:> Description: 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 msg: Exception message if timeout was exceeded :type msg: str """
if not start: # Must provide a comparison time return False if time.time() - start > self.session_timeout: # session_timeout exceeded raise NetMikoTimeoutException(msg) return False
<SYSTEM_TASK:> Try to acquire the Netmiko session lock. If not available, wait in the queue until <END_TASK> <USER_TASK:> Description: 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) """
if not start: start = time.time() # Wait here until the SSH channel lock is acquired or until session_timeout exceeded while not self._session_locker.acquire(False) and not self._timeout_exceeded( start, "The netmiko channel is not available!" ): time.sleep(0.1) return True
<SYSTEM_TASK:> Returns a boolean flag with the state of the connection. <END_TASK> <USER_TASK:> Description: 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: # Try sending IAC + NOP (IAC is telnet way of sending command) # IAC = Interpret as Command; it comes before the NOP. log.debug("Sending IAC + NOP") # Need to send multiple times to test connection self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP) self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP) self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP) return True except AttributeError: return False else: # SSH try: # Try sending ASCII null byte to maintain the connection alive log.debug("Sending the NULL byte") self.write_channel(null) return self.remote_conn.transport.is_active() except (socket.error, EOFError): log.error("Unable to send", exc_info=True) # If unable to send, we can tell for sure that the connection is unusable return False return False
<SYSTEM_TASK:> Function that reads channel until pattern is detected. <END_TASK> <USER_TASK:> Description: 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_BUFFER. In the case of telnet it reads all non-blocking data. There are dependencies here like determining whether in config_mode that are actually depending on reading beyond pattern. :param pattern: Regular expression pattern used to identify the command is done \ (defaults to self.base_prompt) :type pattern: str (regular expression) :param re_flags: regex flags used in conjunction with pattern to search for prompt \ (defaults to no flags) :type re_flags: int :param max_loops: max number of iterations to read the channel before raising exception. Will default to be based upon self.timeout. :type max_loops: int """
output = "" if not pattern: pattern = re.escape(self.base_prompt) log.debug("Pattern is: {}".format(pattern)) i = 1 loop_delay = 0.1 # Default to making loop time be roughly equivalent to self.timeout (support old max_loops # argument for backwards compatibility). if max_loops == 150: max_loops = int(self.timeout / loop_delay) while i < max_loops: if self.protocol == "ssh": try: # If no data available will wait timeout seconds trying to read self._lock_netmiko_session() new_data = self.remote_conn.recv(MAX_BUFFER) if len(new_data) == 0: raise EOFError("Channel stream closed by remote device.") new_data = new_data.decode("utf-8", "ignore") log.debug("_read_channel_expect read_data: {}".format(new_data)) output += new_data self._write_session_log(new_data) except socket.timeout: raise NetMikoTimeoutException( "Timed-out reading channel, data not available." ) finally: self._unlock_netmiko_session() elif self.protocol == "telnet" or "serial": output += self.read_channel() if re.search(pattern, output, flags=re_flags): log.debug("Pattern found: {} {}".format(pattern, output)) return output time.sleep(loop_delay * self.global_delay_factor) i += 1 raise NetMikoTimeoutException( "Timed-out reading channel, pattern not found in output: {}".format(pattern) )
<SYSTEM_TASK:> Read data on the channel based on timing delays. <END_TASK> <USER_TASK:> Description: 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_factor) to make sure reading of channel is complete. :param delay_factor: multiplicative factor to adjust delay when reading channel (delays get multiplied by this factor) :type delay_factor: int or float :param max_loops: maximum number of loops to iterate through before returning channel data. Will default to be based upon self.timeout. :type max_loops: int """
# Time to delay in each read loop loop_delay = 0.1 final_delay = 2 # Default to making loop time be roughly equivalent to self.timeout (support old max_loops # and delay_factor arguments for backwards compatibility). delay_factor = self.select_delay_factor(delay_factor) if delay_factor == 1 and max_loops == 150: max_loops = int(self.timeout / loop_delay) channel_data = "" i = 0 while i <= max_loops: time.sleep(loop_delay * delay_factor) new_data = self.read_channel() if new_data: channel_data += new_data else: # Safeguard to make sure really done time.sleep(final_delay * delay_factor) new_data = self.read_channel() if not new_data: break else: channel_data += new_data i += 1 return channel_data
<SYSTEM_TASK:> Read until either self.base_prompt or pattern is detected. <END_TASK> <USER_TASK:> Description: 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 to \ terminate output reading when the first of self.base_prompt or pattern is detected. :type pattern: regular expression string :param re_flags: regex flags used in conjunction with pattern to search for prompt \ (defaults to no flags) :type re_flags: int """
combined_pattern = re.escape(self.base_prompt) if pattern: combined_pattern = r"({}|{})".format(combined_pattern, pattern) return self._read_channel_expect(combined_pattern, re_flags=re_flags)
<SYSTEM_TASK:> Update SSH connection parameters based on contents of SSH 'config' file. <END_TASK> <USER_TASK:> Description: 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. full_path = path.abspath(path.expanduser(self.ssh_config_file)) if path.exists(full_path): ssh_config_instance = paramiko.SSHConfig() with io.open(full_path, "rt", encoding="utf-8") as f: ssh_config_instance.parse(f) source = ssh_config_instance.lookup(self.host) else: source = {} if "proxycommand" in source: proxy = paramiko.ProxyCommand(source["proxycommand"]) elif "ProxyCommand" in source: proxy = paramiko.ProxyCommand(source["ProxyCommand"]) else: proxy = None # Only update 'hostname', 'sock', 'port', and 'username' # For 'port' and 'username' only update if using object defaults if connect_dict["port"] == 22: connect_dict["port"] = int(source.get("port", self.port)) if connect_dict["username"] == "": connect_dict["username"] = source.get("user", self.username) if proxy: connect_dict["sock"] = proxy connect_dict["hostname"] = source.get("hostname", self.host) return connect_dict
<SYSTEM_TASK:> Generate dictionary of Paramiko connection parameters. <END_TASK> <USER_TASK:> Description: 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, "allow_agent": self.allow_agent, "key_filename": self.key_file, "pkey": self.pkey, "passphrase": self.passphrase, "timeout": self.timeout, "auth_timeout": self.auth_timeout, } # Check if using SSH 'config' file mainly for SSH proxy support if self.ssh_config_file: conn_dict = self._use_ssh_config(conn_dict) return conn_dict
<SYSTEM_TASK:> Strip out command echo, trailing router prompt and ANSI escape codes. <END_TASK> <USER_TASK:> Description: 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: :type strip_command: """
if self.ansi_escape_codes: output = self.strip_ansi_escape_codes(output) output = self.normalize_linefeeds(output) if strip_command and command_string: command_string = self.normalize_linefeeds(command_string) output = self.strip_command(command_string, output) if strip_prompt: output = self.strip_prompt(output) return output
<SYSTEM_TASK:> Establish SSH connection to the network device <END_TASK> <USER_TASK:> Description: 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. :param width: Specified width of the VT100 terminal window :type width: int :param height: Specified height of the VT100 terminal window :type height: int """
if self.protocol == "telnet": self.remote_conn = telnetlib.Telnet( self.host, port=self.port, timeout=self.timeout ) self.telnet_login() elif self.protocol == "serial": self.remote_conn = serial.Serial(**self.serial_settings) self.serial_login() elif self.protocol == "ssh": ssh_connect_params = self._connect_params_dict() self.remote_conn_pre = self._build_ssh_client() # initiate SSH connection try: self.remote_conn_pre.connect(**ssh_connect_params) except socket.error: self.paramiko_cleanup() msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port ) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: self.paramiko_cleanup() msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port ) msg += self.RETURN + text_type(auth_err) raise NetMikoAuthenticationException(msg) if self.verbose: print( "SSH connection established to {}:{}".format(self.host, self.port) ) # Use invoke_shell to establish an 'interactive session' if width and height: self.remote_conn = self.remote_conn_pre.invoke_shell( term="vt100", width=width, height=height ) else: self.remote_conn = self.remote_conn_pre.invoke_shell() self.remote_conn.settimeout(self.blocking_timeout) if self.keepalive: self.remote_conn.transport.set_keepalive(self.keepalive) self.special_login_handler() if self.verbose: print("Interactive SSH session established") return ""
<SYSTEM_TASK:> CLI terminals try to automatically adjust the line based on the width of the terminal. <END_TASK> <USER_TASK:> Description: 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. :param command: Command string to send to the device :type command: str :param delay_factor: See __init__: global_delay_factor :type delay_factor: int """
if not command: return "" delay_factor = self.select_delay_factor(delay_factor) command = self.normalize_cmd(command) self.write_channel(command) output = self.read_until_prompt() if self.ansi_escape_codes: output = self.strip_ansi_escape_codes(output) return output
<SYSTEM_TASK:> Finds the current network device prompt, last line only. <END_TASK> <USER_TASK:> Description: 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.write_channel(self.RETURN) time.sleep(delay_factor * 0.1) # Initial attempt to get prompt prompt = self.read_channel() if self.ansi_escape_codes: prompt = self.strip_ansi_escape_codes(prompt) # Check if the only thing you received was a newline count = 0 prompt = prompt.strip() while count <= 10 and not prompt: prompt = self.read_channel().strip() if prompt: if self.ansi_escape_codes: prompt = self.strip_ansi_escape_codes(prompt).strip() else: self.write_channel(self.RETURN) time.sleep(delay_factor * 0.1) count += 1 # If multiple lines in the output take the last line prompt = self.normalize_linefeeds(prompt) prompt = prompt.split(self.RESPONSE_RETURN)[-1] prompt = prompt.strip() if not prompt: raise ValueError("Unable to find prompt: {}".format(prompt)) time.sleep(delay_factor * 0.1) self.clear_buffer() return prompt
<SYSTEM_TASK:> Execute command_string on the SSH channel using a delay-based mechanism. Generally <END_TASK> <USER_TASK:> Description: 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 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). :type delay_factor: int or float :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be based upon self.timeout. :type max_loops: int :param strip_prompt: Remove the trailing router prompt from the output (default: True). :type strip_prompt: bool :param strip_command: Remove the echo of the command from the output (default: True). :type strip_command: bool :param normalize: Ensure the proper enter is sent at end of command (default: True). :type normalize: bool :param use_textfsm: Process command output through TextFSM template (default: False). :type normalize: bool """
output = "" delay_factor = self.select_delay_factor(delay_factor) self.clear_buffer() if normalize: command_string = self.normalize_cmd(command_string) self.write_channel(command_string) output = self._read_channel_timing( delay_factor=delay_factor, max_loops=max_loops ) output = self._sanitize_output( output, strip_command=strip_command, command_string=command_string, strip_prompt=strip_prompt, ) if use_textfsm: output = get_structured_data( output, platform=self.device_type, command=command_string.strip() ) return output
<SYSTEM_TASK:> In certain situations the first line will get repainted which causes a false <END_TASK> <USER_TASK:> Description: 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 potentially with the first line modified and the first_line_processed is a flag indicating that we have handled the first line. """
try: # First line is the echo line containing the command. In certain situations # it gets repainted and needs filtered lines = data.split(self.RETURN) first_line = lines[0] if BACKSPACE_CHAR in first_line: pattern = search_pattern + r".*$" first_line = re.sub(pattern, repl="", string=first_line) lines[0] = first_line data = self.RETURN.join(lines) return (data, True) except IndexError: return (data, False)
<SYSTEM_TASK:> Execute command_string on the SSH channel using a pattern-based mechanism. Generally <END_TASK> <USER_TASK:> Description: 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 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 command_string: The command to be executed on the remote device. :type command_string: str :param expect_string: Regular expression pattern to use for determining end of output. If left blank will default to being based on router prompt. :type expect_string: str :param delay_factor: Multiplying factor used to adjust delays (default: 1). :type delay_factor: int :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be based upon self.timeout. :type max_loops: int :param strip_prompt: Remove the trailing router prompt from the output (default: True). :type strip_prompt: bool :param strip_command: Remove the echo of the command from the output (default: True). :type strip_command: bool :param normalize: Ensure the proper enter is sent at end of command (default: True). :type normalize: bool :param use_textfsm: Process command output through TextFSM template (default: False). :type normalize: bool """
# Time to delay in each read loop loop_delay = 0.2 # Default to making loop time be roughly equivalent to self.timeout (support old max_loops # and delay_factor arguments for backwards compatibility). delay_factor = self.select_delay_factor(delay_factor) if delay_factor == 1 and max_loops == 500: # Default arguments are being used; use self.timeout instead max_loops = int(self.timeout / loop_delay) # Find the current router prompt if expect_string is None: if auto_find_prompt: try: prompt = self.find_prompt(delay_factor=delay_factor) except ValueError: prompt = self.base_prompt else: prompt = self.base_prompt search_pattern = re.escape(prompt.strip()) else: search_pattern = expect_string if normalize: command_string = self.normalize_cmd(command_string) time.sleep(delay_factor * loop_delay) self.clear_buffer() self.write_channel(command_string) i = 1 output = "" past_three_reads = deque(maxlen=3) first_line_processed = False # Keep reading data until search_pattern is found or until max_loops is reached. while i <= max_loops: new_data = self.read_channel() if new_data: if self.ansi_escape_codes: new_data = self.strip_ansi_escape_codes(new_data) output += new_data past_three_reads.append(new_data) # Case where we haven't processed the first_line yet (there is a potential issue # in the first line (in cases where the line is repainted). if not first_line_processed: output, first_line_processed = self._first_line_handler( output, search_pattern ) # Check if we have already found our pattern if re.search(search_pattern, output): break else: # Check if pattern is in the past three reads if re.search(search_pattern, "".join(past_three_reads)): break time.sleep(delay_factor * loop_delay) i += 1 else: # nobreak raise IOError( "Search pattern never detected in send_command_expect: {}".format( search_pattern ) ) output = self._sanitize_output( output, strip_command=strip_command, command_string=command_string, strip_prompt=strip_prompt, ) if use_textfsm: output = get_structured_data( output, platform=self.device_type, command=command_string.strip() ) return output
<SYSTEM_TASK:> Strip command_string from output string <END_TASK> <USER_TASK:> Description: 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 :param output: The returned output as a result of the command string sent to the device :type output: str """
backspace_char = "\x08" # Check for line wrap (remove backspaces) if backspace_char in output: output = output.replace(backspace_char, "") output_lines = output.split(self.RESPONSE_RETURN) new_output = output_lines[1:] return self.RESPONSE_RETURN.join(new_output) else: command_length = len(command_string) return output[command_length:]
<SYSTEM_TASK:> Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.` <END_TASK> <USER_TASK:> Description: 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|\r\n|\n\r)") a_string = newline.sub(self.RESPONSE_RETURN, a_string) if self.RESPONSE_RETURN == "\n": # Convert any remaining \r to \n return re.sub("\r", self.RESPONSE_RETURN, a_string)
<SYSTEM_TASK:> Normalize CLI commands to have a single trailing newline. <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Check if in enable mode. Return boolean. <END_TASK> <USER_TASK:> Description: 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_string in output
<SYSTEM_TASK:> Enter into config_mode. <END_TASK> <USER_TASK:> Description: 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 = "" if not self.check_config_mode(): self.write_channel(self.normalize_cmd(config_command)) output = self.read_until_pattern(pattern=pattern) if not self.check_config_mode(): raise ValueError("Failed to enter configuration mode.") return output
<SYSTEM_TASK:> Send configuration commands down the SSH channel from a file. <END_TASK> <USER_TASK:> Description: 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_file: Path to configuration file to be sent to the device :type config_file: str :param kwargs: params to be sent to send_config_set method :type kwargs: dict """
with io.open(config_file, "rt", encoding="utf-8") as cfg_file: return self.send_config_set(cfg_file, **kwargs)
<SYSTEM_TASK:> Send configuration commands down the SSH channel. <END_TASK> <USER_TASK:> Description: 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. 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 be sent to the device :type config_commands: list or string :param exit_config_mode: Determines whether or not to exit config mode after complete :type exit_config_mode: bool :param delay_factor: Factor to adjust delays :type delay_factor: int :param max_loops: Controls wait time in conjunction with delay_factor (default: 150) :type max_loops: int :param strip_prompt: Determines whether or not to strip the prompt :type strip_prompt: bool :param strip_command: Determines whether or not to strip the command :type strip_command: bool :param config_mode_command: The command to enter into config mode :type config_mode_command: str """
delay_factor = self.select_delay_factor(delay_factor) if config_commands is None: return "" elif isinstance(config_commands, string_types): config_commands = (config_commands,) if not hasattr(config_commands, "__iter__"): raise ValueError("Invalid argument passed into send_config_set") # Send config commands cfg_mode_args = (config_mode_command,) if config_mode_command else tuple() output = self.config_mode(*cfg_mode_args) for cmd in config_commands: self.write_channel(self.normalize_cmd(cmd)) if self.fast_cli: pass else: time.sleep(delay_factor * 0.05) # Gather output output += self._read_channel_timing( delay_factor=delay_factor, max_loops=max_loops ) if exit_config_mode: output += self.exit_config_mode() output = self._sanitize_output(output) log.debug("{}".format(output)) return output
<SYSTEM_TASK:> Try to gracefully close the SSH connection. <END_TASK> <USER_TASK:> Description: 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 == "serial": self.remote_conn.close() except Exception: # There have been race conditions observed on disconnect. pass finally: self.remote_conn_pre = None self.remote_conn = None self.close_session_log()
<SYSTEM_TASK:> For all telnet options, re-implement the default telnetlib behaviour <END_TASK> <USER_TASK:> Description: 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 command == DO and option == TTYPE: tsocket.sendall(IAC + WILL + TTYPE) tsocket.sendall(IAC + SB + TTYPE + b"\0" + b"xterm" + IAC + SE) elif command in (DO, DONT): tsocket.sendall(IAC + WONT + option) elif command in (WILL, WONT): tsocket.sendall(IAC + DONT + option)
<SYSTEM_TASK:> Disable paging is only available with specific roles so it may fail. <END_TASK> <USER_TASK:> Description: 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 self._output_mode = "more" if "Virtual domain configuration: enable" in output: self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) if "Command fail" in output: self.allow_disable_global = False self.remote_conn.close() self.establish_connection(width=100, height=1000) new_output = "" if self.allow_disable_global: self._retrieve_output_mode() disable_paging_commands = [ "config system console", "set output standard", "end", ] # There is an extra 'end' required if in multi-vdoms are enabled if self.vdoms: disable_paging_commands.append("end") outputlist = [ self.send_command_timing(command, delay_factor=2) for command in disable_paging_commands ] # Should test output is valid new_output = self.RETURN.join(outputlist) return output + new_output
<SYSTEM_TASK:> Save the state of the output mode so it can be reset at the end of the session. <END_TASK> <USER_TASK:> Description: 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: result_mode = result_mode_re.group("mode").strip() if result_mode in ["more", "standard"]: self._output_mode = result_mode
<SYSTEM_TASK:> Prepare the session after the connection has been established. <END_TASK> <USER_TASK:> Description: 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: output += self.read_channel() if "any key to continue" in output: self.write_channel(self.RETURN) break else: time.sleep(0.33 * delay_factor) count += 1 # Try one last time to past "Press any key to continue self.write_channel(self.RETURN) # HP output contains VT100 escape codes self.ansi_escape_codes = True self._test_channel_read(pattern=r"[>#]") self.set_base_prompt() command = self.RETURN + "no page" self.disable_paging(command=command) self.set_terminal_width(command="terminal width 511") # Clear the read buffer time.sleep(0.3 * self.global_delay_factor) self.clear_buffer()
<SYSTEM_TASK:> tmsh command is equivalent to config command on F5. <END_TASK> <USER_TASK:> Description: 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_factor) self.clear_buffer() return None
<SYSTEM_TASK:> Remove the > when navigating into the different config level. <END_TASK> <USER_TASK:> Description: def set_base_prompt(self, *args, **kwargs): """Remove the > when navigating into the different config level."""
cur_base_prompt = super(AlcatelSrosSSH, self).set_base_prompt(*args, **kwargs) match = re.search(r"(.*)(>.*)*#", cur_base_prompt) if match: # strip off >... from base_prompt self.base_prompt = match.group(1) return self.base_prompt
<SYSTEM_TASK:> Enter into configuration mode on SROS device. <END_TASK> <USER_TASK:> Description: def config_mode(self, config_command="configure", pattern="#"): """ Enter into configuration mode on SROS device."""
return super(AlcatelSrosSSH, self).config_mode( config_command=config_command, pattern=pattern )
<SYSTEM_TASK:> Extreme attaches an id to the prompt. The id increases with every command. <END_TASK> <USER_TASK:> Description: def set_base_prompt(self, *args, **kwargs): """ Extreme attaches an id to the prompt. The id increases with every command. It needs to br stripped off to match the prompt. Eg. testhost.1 # testhost.2 # testhost.3 # If new config is loaded and not saved yet, a '* ' prefix appears before the prompt, eg. * testhost.4 # * testhost.5 # """
cur_base_prompt = super(ExtremeExosBase, self).set_base_prompt(*args, **kwargs) # Strip off any leading * or whitespace chars; strip off trailing period and digits match = re.search(r"[\*\s]*(.*)\.\d+", cur_base_prompt) if match: self.base_prompt = match.group(1) return self.base_prompt else: return self.base_prompt
<SYSTEM_TASK:> Extreme needs special handler here due to the prompt changes. <END_TASK> <USER_TASK:> Description: def send_command(self, *args, **kwargs): """Extreme needs special handler here due to the prompt changes."""
# Change send_command behavior to use self.base_prompt kwargs.setdefault("auto_find_prompt", False) # refresh self.base_prompt self.set_base_prompt() return super(ExtremeExosBase, self).send_command(*args, **kwargs)
<SYSTEM_TASK:> Strip Juniper-specific output. <END_TASK> <USER_TASK:> Description: def strip_context_items(self, a_string): """Strip Juniper-specific output. Juniper will also put a configuration context: [edit] and various chassis contexts: {master:0}, {backup:1} This method removes those lines. """
strings_to_strip = [ r"\[edit.*\]", r"\{master:.*\}", r"\{backup:.*\}", r"\{line.*\}", r"\{primary.*\}", r"\{secondary.*\}", ] response_list = a_string.split(self.RESPONSE_RETURN) last_line = response_list[-1] for pattern in strings_to_strip: if re.search(pattern, last_line): return self.RESPONSE_RETURN.join(response_list[:-1]) return a_string
<SYSTEM_TASK:> Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text. <END_TASK> <USER_TASK:> Description: def normalize_linefeeds(self, a_string): """Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n|\r\n)") # NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS) return newline.sub(self.RESPONSE_RETURN, a_string).replace("\r", "\n")
<SYSTEM_TASK:> Send command to network device retrieve output until router_prompt or expect_string <END_TASK> <USER_TASK:> Description: def send_command(self, *args, **kwargs): """ Send command to network device retrieve output until router_prompt or expect_string 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. command_string = command to execute expect_string = pattern to search for uses re.search (use raw strings) delay_factor = decrease the initial delay before we start looking for data max_loops = number of iterations before we give up and raise an exception strip_prompt = strip the trailing prompt from the output strip_command = strip the leading command from the output """
if len(args) >= 2: expect_string = args[1] else: expect_string = kwargs.get("expect_string") if expect_string is None: expect_string = r"(OK|ERROR|Command not recognized\.)" expect_string = self.RETURN + expect_string + self.RETURN kwargs.setdefault("expect_string", expect_string) output = super(CiscoSSHConnection, self).send_command(*args, **kwargs) return output
<SYSTEM_TASK:> Use processes and Netmiko to connect to each of the devices. Execute <END_TASK> <USER_TASK:> Description: def main(): """ Use processes and Netmiko to connect to each of the devices. Execute 'show version' on each device. Record the amount of time required to do this. """
start_time = datetime.now() procs = [] for a_device in devices: my_proc = Process(target=show_version, args=(a_device,)) my_proc.start() procs.append(my_proc) for a_proc in procs: print(a_proc) a_proc.join() print("\nElapsed time: " + str(datetime.now() - start_time))
<SYSTEM_TASK:> Get an item from the Row by column name. <END_TASK> <USER_TASK:> Description: def get(self, column, default_value=None): """Get an item from the Row by column name. Args: column: Tuple of column names, or a (str) column name, or positional column number, 0-indexed. default_value: The value to use if the key is not found. Returns: A list or string with column value(s) or default_value if not found. """
if isinstance(column, (list, tuple)): ret = [] for col in column: ret.append(self.get(col, default_value)) return ret # Perhaps we have a range like '1', ':-1' or '1:'. try: return self._values[column] except (IndexError, TypeError): pass try: return self[column] except IndexError: return default_value
<SYSTEM_TASK:> Sets row's colour attributes to a list of values in terminal.SGR. <END_TASK> <USER_TASK:> Description: def _SetColour(self, value_list): """Sets row's colour attributes to a list of values in terminal.SGR."""
if value_list is None: self._color = None return colors = [] for color in value_list: if color in terminal.SGR: colors.append(color) elif color in terminal.FG_COLOR_WORDS: colors += terminal.FG_COLOR_WORDS[color] elif color in terminal.BG_COLOR_WORDS: colors += terminal.BG_COLOR_WORDS[color] else: raise ValueError("Invalid colour specification.") self._color = list(set(colors))
<SYSTEM_TASK:> Inserts new values at a specified offset. <END_TASK> <USER_TASK:> Description: def Insert(self, key, value, row_index): """Inserts new values at a specified offset. Args: key: string for header value. value: string for a data value. row_index: Offset into row for data. Raises: IndexError: If the offset is out of bands. """
if row_index < 0: row_index += len(self) if not 0 <= row_index < len(self): raise IndexError('Index "%s" is out of bounds.' % row_index) new_row = Row() for idx in self.header: if self.index(idx) == row_index: new_row[key] = value new_row[idx] = self[idx] self._keys = new_row.header self._values = new_row.values del new_row self._BuildIndex()
<SYSTEM_TASK:> Applies the function to every row in the table. <END_TASK> <USER_TASK:> Description: def Map(self, function): """Applies the function to every row in the table. Args: function: A function applied to each row. Returns: A new TextTable() Raises: TableError: When transform is not invalid row entry. The transform must be compatible with Append(). """
new_table = self.__class__() # pylint: disable=protected-access new_table._table = [self.header] for row in self: filtered_row = function(row) if filtered_row: new_table.Append(filtered_row) return new_table
<SYSTEM_TASK:> Sorts rows in the texttable. <END_TASK> <USER_TASK:> Description: def sort(self, cmp=None, key=None, reverse=False): """Sorts rows in the texttable. Args: cmp: func, non default sort algorithm to use. key: func, applied to each element before sorting. reverse: bool, reverse order of sort. """
def _DefaultKey(value): """Default key func is to create a list of all fields.""" result = [] for key in self.header: # Try sorting as numerical value if possible. try: result.append(float(value[key])) except ValueError: result.append(value[key]) return result key = key or _DefaultKey # Exclude header by copying table. new_table = self._table[1:] if cmp is not None: key = cmp_to_key(cmp) new_table.sort(key=key, reverse=reverse) # Regenerate the table with original header self._table = [self.header] self._table.extend(new_table) # Re-write the 'row' attribute of each row for index, row in enumerate(self._table): row.row = index
<SYSTEM_TASK:> Extends all rows in the texttable. <END_TASK> <USER_TASK:> Description: def extend(self, table, keys=None): """Extends all rows in the texttable. The rows are extended with the new columns from the table. Args: table: A texttable, the table to extend this table by. keys: A set, the set of columns to use as the key. If None, the row index is used. Raises: IndexError: If key is not a valid column name. """
if keys: for k in keys: if k not in self._Header(): raise IndexError("Unknown key: '%s'", k) extend_with = [] for column in table.header: if column not in self.header: extend_with.append(column) if not extend_with: return for column in extend_with: self.AddColumn(column) if not keys: for row1, row2 in zip(self, table): for column in extend_with: row1[column] = row2[column] return for row1 in self: for row2 in table: for k in keys: if row1[k] != row2[k]: break else: for column in extend_with: row1[column] = row2[column] break
<SYSTEM_TASK:> Removes a row from the table. <END_TASK> <USER_TASK:> Description: def Remove(self, row): """Removes a row from the table. Args: row: int, the row number to delete. Must be >= 1, as the header cannot be removed. Raises: TableError: Attempt to remove nonexistent or header row. """
if row == 0 or row > self.size: raise TableError("Attempt to remove header row") new_table = [] # pylint: disable=E1103 for t_row in self._table: if t_row.row != row: new_table.append(t_row) if t_row.row > row: t_row.row -= 1 self._table = new_table
<SYSTEM_TASK:> Returns the current row as a tuple. <END_TASK> <USER_TASK:> Description: def _GetRow(self, columns=None): """Returns the current row as a tuple."""
row = self._table[self._row_index] if columns: result = [] for col in columns: if col not in self.header: raise TableError("Column header %s not known in table." % col) result.append(row[self.header.index(col)]) row = result return row
<SYSTEM_TASK:> Sets the current row to new list. <END_TASK> <USER_TASK:> Description: def _SetRow(self, new_values, row=0): """Sets the current row to new list. Args: new_values: List|dict of new values to insert into row. row: int, Row to insert values into. Raises: TableError: If number of new values is not equal to row size. """
if not row: row = self._row_index if row > self.size: raise TableError("Entry %s beyond table size %s." % (row, self.size)) self._table[row].values = new_values
<SYSTEM_TASK:> Sets header of table to the given tuple. <END_TASK> <USER_TASK:> Description: def _SetHeader(self, new_values): """Sets header of table to the given tuple. Args: new_values: Tuple of new header values. """
row = self.row_class() row.row = 0 for v in new_values: row[v] = v self._table[0] = row
<SYSTEM_TASK:> Finds the largest indivisible word of a string. <END_TASK> <USER_TASK:> Description: def _SmallestColSize(self, text): """Finds the largest indivisible word of a string. ...and thus the smallest possible column width that can contain that word unsplit over rows. Args: text: A string of text potentially consisting of words. Returns: Integer size of the largest single word in the text. """
if not text: return 0 stripped = terminal.StripAnsiText(text) return max(len(word) for word in stripped.split())
<SYSTEM_TASK:> Retrieves the first non header row with the column of the given value. <END_TASK> <USER_TASK:> Description: def RowWith(self, column, value): """Retrieves the first non header row with the column of the given value. Args: column: str, the name of the column to check. value: str, The value of the column to check. Returns: A Row() of the first row found, None otherwise. Raises: IndexError: The specified column does not exist. """
for row in self._table[1:]: if row[column] == value: return row return None
<SYSTEM_TASK:> Appends a new column to the table. <END_TASK> <USER_TASK:> Description: def AddColumn(self, column, default="", col_index=-1): """Appends a new column to the table. Args: column: A string, name of the column to add. default: Default value for entries. Defaults to ''. col_index: Integer index for where to insert new column. Raises: TableError: Column name already exists. """
if column in self.table: raise TableError("Column %r already in table." % column) if col_index == -1: self._table[0][column] = column for i in range(1, len(self._table)): self._table[i][column] = default else: self._table[0].Insert(column, column, col_index) for i in range(1, len(self._table)): self._table[i].Insert(column, default, col_index)
<SYSTEM_TASK:> Fetches a new, empty row, with headers populated. <END_TASK> <USER_TASK:> Description: def NewRow(self, value=""): """Fetches a new, empty row, with headers populated. Args: value: Initial value to set each row entry to. Returns: A Row() object. """
newrow = self.row_class() newrow.row = self.size + 1 newrow.table = self headers = self._Header() for header in headers: newrow[header] = value return newrow
<SYSTEM_TASK:> Parses buffer into tabular format. <END_TASK> <USER_TASK:> Description: def CsvToTable(self, buf, header=True, separator=","): """Parses buffer into tabular format. Strips off comments (preceded by '#'). Optionally parses and indexes by first line (header). Args: buf: String file buffer containing CSV data. header: Is the first line of buffer a header. separator: String that CSV is separated by. Returns: int, the size of the table created. Raises: TableError: A parsing error occurred. """
self.Reset() header_row = self.row_class() if header: line = buf.readline() header_str = "" while not header_str: # Remove comments. header_str = line.split("#")[0].strip() if not header_str: line = buf.readline() header_list = header_str.split(separator) header_length = len(header_list) for entry in header_list: entry = entry.strip() if entry in header_row: raise TableError("Duplicate header entry %r." % entry) header_row[entry] = entry header_row.row = 0 self._table[0] = header_row # xreadlines would be better but not supported by StringIO for testing. for line in buf: # Support commented lines, provide '#' is first character of line. if line.startswith("#"): continue lst = line.split(separator) lst = [l.strip() for l in lst] if header and len(lst) != header_length: # Silently drop illegal line entries continue if not header: header_row = self.row_class() header_length = len(lst) header_row.values = dict( zip(range(header_length), range(header_length)) ) self._table[0] = header_row header = True continue new_row = self.NewRow() new_row.values = lst header_row.row = self.size + 1 self._table.append(new_row) return self.size
<SYSTEM_TASK:> Make sure paging is disabled. <END_TASK> <USER_TASK:> Description: def disable_paging(self, command="pager off", delay_factor=1): """Make sure paging is disabled."""
return super(PluribusSSH, self).disable_paging( command=command, delay_factor=delay_factor )
<SYSTEM_TASK:> Print out inventory devices and groups. <END_TASK> <USER_TASK:> Description: def display_inventory(my_devices): """Print out inventory devices and groups."""
inventory_groups = ["all"] inventory_devices = [] for k, v in my_devices.items(): if isinstance(v, list): inventory_groups.append(k) elif isinstance(v, dict): inventory_devices.append((k, v["device_type"])) inventory_groups.sort() inventory_devices.sort(key=lambda x: x[0]) print("\nDevices:") print("-" * 40) for a_device, device_type in inventory_devices: device_type = " ({})".format(device_type) print("{:<25}{:>15}".format(a_device, device_type)) print("\n\nGroups:") print("-" * 40) for a_group in inventory_groups: print(a_group) print()
<SYSTEM_TASK:> Dynamically create 'all' group. <END_TASK> <USER_TASK:> Description: def obtain_all_devices(my_devices): """Dynamically create 'all' group."""
new_devices = {} for device_name, device_or_group in my_devices.items(): # Skip any groups if not isinstance(device_or_group, list): new_devices[device_name] = device_or_group return new_devices
<SYSTEM_TASK:> Ensure directory exists. Create if necessary. <END_TASK> <USER_TASK:> Description: def ensure_dir_exists(verify_dir): """Ensure directory exists. Create if necessary."""
if not os.path.exists(verify_dir): # Doesn't exist create dir os.makedirs(verify_dir) else: # Exists if not os.path.isdir(verify_dir): # Not a dir, raise an exception raise ValueError("{} is not a directory".format(verify_dir))
<SYSTEM_TASK:> Write Python2 and Python3 compatible byte stream. <END_TASK> <USER_TASK:> Description: def write_bytes(out_data, encoding="ascii"): """Write Python2 and Python3 compatible byte stream."""
if sys.version_info[0] >= 3: if isinstance(out_data, type("")): if encoding == "utf-8": return out_data.encode("utf-8") else: return out_data.encode("ascii", "ignore") elif isinstance(out_data, type(b"")): return out_data else: if isinstance(out_data, type("")): if encoding == "utf-8": return out_data.encode("utf-8") else: return out_data.encode("ascii", "ignore") elif isinstance(out_data, type(str(""))): return out_data msg = "Invalid value for out_data neither unicode nor byte string: {}".format( out_data ) raise ValueError(msg)
<SYSTEM_TASK:> Given a file name to a valid file returns the file object. <END_TASK> <USER_TASK:> Description: def file_contents(file_name): """Given a file name to a valid file returns the file object."""
curr_dir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(curr_dir, file_name)) as the_file: contents = the_file.read() return contents
<SYSTEM_TASK:> Handles using .title if the given object is a troposphere resource. <END_TASK> <USER_TASK:> Description: def depends_on_helper(obj): """ Handles using .title if the given object is a troposphere resource. If the given object is a troposphere resource, use the `.title` attribute of that resource. If it's a string, just use the string. This should allow more pythonic use of DependsOn. """
if isinstance(obj, AWSObject): return obj.title elif isinstance(obj, list): return list(map(depends_on_helper, obj)) return obj
<SYSTEM_TASK:> Imports userdata from a file. <END_TASK> <USER_TASK:> Description: def from_file(filepath, delimiter='', blanklines=False): """Imports userdata from a file. :type filepath: string :param filepath The absolute path to the file. :type delimiter: string :param: delimiter Delimiter to use with the troposphere.Join(). :type blanklines: boolean :param blanklines If blank lines shoud be ignored rtype: troposphere.Base64 :return The base64 representation of the file. """
data = [] try: with open(filepath, 'r') as f: for line in f: if blanklines and line.strip('\n\r ') == '': continue data.append(line) except IOError: raise IOError('Error opening or reading file: {}'.format(filepath)) return Base64(Join(delimiter, data))
<SYSTEM_TASK:> Return a list of validators specified in the override file <END_TASK> <USER_TASK:> Description: def get_validator_list(self): """Return a list of validators specified in the override file"""
ignore = [ 'dict', ] vlist = [] if not self.override: return vlist for k, v in list(self.override['classes'].items()): if 'validator' in v: validator = v['validator'] if validator not in ignore and validator not in vlist: vlist.append(validator) for k, v in list(self.override['classes'].items()): for kp, vp in list(v.items()): if 'validator' in vp: validator = vp['validator'] if validator not in ignore and validator not in vlist: vlist.append(validator) return sorted(vlist)
<SYSTEM_TASK:> Look for a Tags object to output a Tags import <END_TASK> <USER_TASK:> Description: def _output_tags(self): """Look for a Tags object to output a Tags import"""
for class_name, properties in sorted(self.resources.items()): for key, value in sorted(properties.items()): validator = self.override.get_validator(class_name, key) if key == 'Tags' and validator is None: print("from troposphere import Tags") return for class_name, properties in sorted(self.properties.items()): for key, value in sorted(properties.items()): validator = self.override.get_validator(class_name, key) if key == 'Tags' and validator is None: print("from troposphere import Tags") return
<SYSTEM_TASK:> Decode a properties type looking for a specific type. <END_TASK> <USER_TASK:> Description: def _check_type(self, check_type, properties): """Decode a properties type looking for a specific type."""
if 'PrimitiveType' in properties: return properties['PrimitiveType'] == check_type if properties['Type'] == 'List': if 'ItemType' in properties: return properties['ItemType'] == check_type else: return properties['PrimitiveItemType'] == check_type return False