INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Get a representation of the ring buffer for plotting. This is expensive, so it should only be used in frontend :return:
def view_data(self): """ Get a representation of the ring buffer for plotting. This is expensive, so it should only be used in frontend :return: """ left, right = self.left_index, self.left_index + len(self) if left > right: left, right = right, left ...
Push values to buffer. If buffer can't store all values a ValueError is raised
def push(self, values: np.ndarray): """ Push values to buffer. If buffer can't store all values a ValueError is raised """ n = len(values) if len(self) + n > self.size: raise ValueError("Too much data to push to RingBuffer") slide_1 = np.s_[self.right_index:m...
Pop number of elements. If there are not enough elements, all remaining elements are returned and the buffer is cleared afterwards. If buffer is empty, an empty numpy array is returned. If number is -1 (or any other value below zero) than complete buffer is returned
def pop(self, number: int, ensure_even_length=False): """ Pop number of elements. If there are not enough elements, all remaining elements are returned and the buffer is cleared afterwards. If buffer is empty, an empty numpy array is returned. If number is -1 (or any other value below z...
XOR Data Whitening :param decoding: :param inpt: :return:
def code_data_whitening(self, decoding, inpt): """ XOR Data Whitening :param decoding: :param inpt: :return: """ inpt_copy = array.array("B", inpt) return self.apply_data_whitening(decoding, inpt_copy)
:type parent: QTableView :type undo_stack: QUndoStack
def get_action(self, parent, undo_stack: QUndoStack, sel_range, protocol, view: int): """ :type parent: QTableView :type undo_stack: QUndoStack """ self.command = ZeroHideAction(protocol, self.following_zeros, view, self.zero_hide_offsets) action = QAction(self.command.te...
Scrolls the mouse if ROI Selection reaches corner of view :param mouse_x: :return:
def scroll_mouse(self, mouse_x: int): """ Scrolls the mouse if ROI Selection reaches corner of view :param mouse_x: :return: """ scrollbar = self.horizontalScrollBar() if mouse_x - self.view_rect().x() > self.view_rect().width(): scrollbar.setValue(s...
Refresh selection area in case scene was resized/scaled. This happens e.g. when switching from Signal View to Quad Demod view :return:
def refresh_selection_area(self): """ Refresh selection area in case scene was resized/scaled. This happens e.g. when switching from Signal View to Quad Demod view :return: """ self.__set_selection_area(x=self.selection_area.x, y=self.selection_area.y, ...
Return the boundaries of the view in scene coordinates
def view_rect(self) -> QRectF: """ Return the boundaries of the view in scene coordinates """ top_left = self.mapToScene(0, 0) bottom_right = self.mapToScene(self.viewport().width() - 1, self.viewport().height() - 1) return QRectF(top_left, bottom_right)
:type: list of ProtocolTreeItem
def dropEvent(self, event: QDropEvent): items = [item for item in self.items(event.scenePos()) if isinstance(item, GraphicsItem) and item.acceptDrops()] item = None if len(items) == 0 else items[0] if len(event.mimeData().urls()) > 0: self.files_dropped.emit(event.mimeData().urls()) ...
Convert bit array to string :param endianness: Endianness little or big :param bits: Bit array :param output_view_type: Output view type index 0 = bit, 1=hex, 2=ascii, 3=decimal 4=binary coded decimal (bcd) :param pad_zeros: :param lsb: Least Significant Bit -> Reverse bits first :param ls...
def convert_bits_to_string(bits, output_view_type: int, pad_zeros=False, lsb=False, lsd=False, endianness="big"): """ Convert bit array to string :param endianness: Endianness little or big :param bits: Bit array :param output_view_type: Output view type index 0 = bit, 1=hex, 2=ascii, 3=decimal ...
In case of ASK modulation, this method tries to use pauses after messages as zero bits so that the bit lengths of messages are divisible by divisor :param bit_data: List of bit arrays :param bit_len: Bit length that was used for demodulation :param pauses: List of pauses :param b...
def __ensure_message_length_multiple(bit_data, bit_len: int, pauses, bit_sample_pos, divisor: int): """ In case of ASK modulation, this method tries to use pauses after messages as zero bits so that the bit lengths of messages are divisible by divisor :param bit_data: List of bit arrays ...
Determine on which place (regarding samples) a bit sequence is :rtype: tuple[int,int]
def get_samplepos_of_bitseq(self, start_message: int, start_index: int, end_message: int, end_index: int, include_pause: bool): """ Determine on which place (regarding samples) a bit sequence is :rtype: tuple[int,int] """ try: if start_...
get start and end index of bit sequence from selected samples :rtype: tuple[int,int,int,int] :return: start_message index, start index, end message index, end index
def get_bitseq_from_selection(self, selection_start: int, selection_width: int): """ get start and end index of bit sequence from selected samples :rtype: tuple[int,int,int,int] :return: start_message index, start index, end message index, end index """ start_message, st...
Konvertiert einen Index aus der einen Sicht (z.B. Bit) in eine andere (z.B. Hex) :param message_indx: if -1, the message with max length is chosen :return:
def convert_index(self, index: int, from_view: int, to_view: int, decoded: bool, message_indx=-1) -> tuple: """ Konvertiert einen Index aus der einen Sicht (z.B. Bit) in eine andere (z.B. Hex) :param message_indx: if -1, the message with max length is chosen :return: """ ...
Calculates the frequency of at most nbits logical ones and returns the mean of these frequencies :param nbits: :return:
def estimate_frequency_for_one(self, sample_rate: float, nbits=42) -> float: """ Calculates the frequency of at most nbits logical ones and returns the mean of these frequencies :param nbits: :return: """ return self.__estimate_frequency_for_bit(True, sample_rate, nbits)
Calculates the frequency of at most nbits logical zeros and returns the mean of these frequencies :param nbits: :return:
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, nbi...
:type decodings: list of Encoding
def auto_assign_decodings(self, decodings): """ :type decodings: list of Encoding """ nrz_decodings = [decoding for decoding in decodings if decoding.is_nrz or decoding.is_nrzi] fallback = nrz_decodings[0] if nrz_decodings else None candidate_decodings = [decoding for dec...
:rtype: int, int
def selection_range(self): """ :rtype: int, int """ selected = self.selectionModel().selection() """:type: QItemSelection """ if selected.isEmpty(): return -1, -1 min_row = min(rng.top() for rng in selected) max_row = max(rng.bottom() for rng...
Remove all cache directories :return:
def cleanup(): """ Remove all cache directories :return: """ script_dir = os.path.dirname(__file__) if not os.path.islink(__file__) else os.path.dirname(os.readlink(__file__)) script_dir = os.path.realpath(os.path.join(script_dir, "..")) shutil.rmtree(os.path.join(script_dir, "dist"), ignore...
:rtype: int, int, int, int
def selection_range(self): """ :rtype: int, int, int, int """ selected = self.selectionModel().selection() # type: QItemSelection if self.selection_is_empty: return -1, -1, -1, -1 def range_to_tuple(rng): return rng.row(), rng.column() t...
Return the most frequent value in list. If there is no unique one, return the maximum of the most frequent values :param values: :return:
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, ...
Get the list of start, end indices of messages :param magnitudes: Magnitudes of samples :param noise_threshold: Threshold for noise :return:
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_magni...
Round plateau lengths to next divisible number of digit count e.g. 99 -> 100, 293 -> 300 :param plateau_lengths: :return:
def round_plateau_lengths(plateau_lengths: list): """ Round plateau lengths to next divisible number of digit count e.g. 99 -> 100, 293 -> 300 :param plateau_lengths: :return: """ # round to n_digits of most common value digit_counts = [len(str(p)) for p in plateau_lengths] n_digits = m...
:param group_id: :type files: list of QtCore.QUrl
def on_files_dropped_on_group(self, files, group_id: int): """ :param group_id: :type files: list of QtCore.QUrl """ self.__add_urls_to_group(files, group_id=group_id)
:rtype: list of Plugin
def load_installed_plugins(self): """ :rtype: list of Plugin """ result = [] plugin_dirs = [d for d in os.listdir(self.plugin_path) if os.path.isdir(os.path.join(self.plugin_path, d))] settings = constants.SETTINGS for d in plugin_dirs: if d == "__pycache__": ...
:rtype: list[tuple of int]
def __get_zero_seq_indexes(self, message: str, following_zeros: int): """ :rtype: list[tuple of int] """ result = [] if following_zeros > len(message): return result zero_counter = 0 for i in range(0, len(message)): if message[i] == "0": ...
returns a string of new device messages separated by newlines :return:
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(error...
:type parent: QTableView :type undo_stack: QUndoStack :type groups: list of ProtocolGroups
def get_action(self, parent, undo_stack: QUndoStack, sel_range, groups, view: int) -> QUndoCommand: """ :type parent: QTableView :type undo_stack: QUndoStack :type groups: list of ProtocolGroups """ raise NotImplementedError("Abstract Method.")
Get the checksum for a WSP message. There are three hashes possible: 1) 4 Bit Checksum - For Switch Telegram (RORG=5 or 6 and STATUS = 0x20 or 0x30) 2) 8 Bit Checksum: STATUS bit 2^7 = 0 3) 8 Bit CRC: STATUS bit 2^7 = 1 :param msg: the message without Preamble/SOF and EOF. Message start...
def calculate(self, msg: array.array) -> array.array: """ Get the checksum for a WSP message. There are three hashes possible: 1) 4 Bit Checksum - For Switch Telegram (RORG=5 or 6 and STATUS = 0x20 or 0x30) 2) 8 Bit Checksum: STATUS bit 2^7 = 0 3) 8 Bit CRC: STATUS bit 2^7 = 1 ...
:type number: int :rtype: ProtocolTreeItem
def child(self, number): """ :type number: int :rtype: ProtocolTreeItem """ if number < self.childCount(): return self.__childItems[number] else: return False
Convenience function for creating a ready-to-go CloudflareScraper object.
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 ...
Convenience function for building a Cookie HTTP header value.
def get_cookie_string(cls, url, user_agent=None, **kwargs): """ Convenience function for building a Cookie HTTP header value. """ tokens, user_agent = cls.get_tokens(url, user_agent=user_agent, **kwargs) return "; ".join("=".join(pair) for pair in tokens.items()), user_agent
Save Config
def save_config(self, cmd="save config", confirm=False, confirm_response=""): """Save Config""" return super(ExtremeErsSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Adding a delay after login.
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)
Save Config for Extreme SLX.
def save_config( self, cmd="copy running-config startup-config", confirm=True, confirm_response="y", ): """Save Config for Extreme SLX.""" return super(ExtremeSlxSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Execute show version command using Netmiko.
def show_version(a_device): """Execute show version command using Netmiko.""" remote_conn = ConnectHandler(**a_device) print() print("#" * 80) print(remote_conn.send_command_expect("show version")) print("#" * 80) print()
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.
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,)) ...
Saves Config
def save_config( self, cmd="copy running-configuration startup-configuration", confirm=False, confirm_response="", ): """Saves Config""" return super(DellForce10SSH, 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.""" # 0 will defer to the global delay factor delay_factor = self.select_delay_factor(delay_factor=0) self._test_channel_read() self.set_base_prompt() cmd = "{}set cli mode -pa...
Strip 'Done' from command output
def strip_prompt(self, a_string): """ Strip 'Done' from command output """ output = super(NetscalerSSH, self).strip_prompt(a_string) lines = output.split(self.RESPONSE_RETURN) if "Done" in lines[-1]: return self.RESPONSE_RETURN.join(lines[:-1]) else: retur...
Saves configuration.
def save_config(self, cmd="write memory", confirm=False, confirm_response=""): """Saves configuration.""" return super(UbiquitiEdgeSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Establish the secure copy connection.
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....
Return space available on remote device.
def remote_space_available(self, search_pattern=r"(\d+) \w+ free"): """Return space available on remote device.""" remote_cmd = "dir {}".format(self.file_system) remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd) match = re.search(search_pattern, remote_output) if ...
Return space available on *nix system (BSD/Linux).
def _remote_space_available_unix(self, search_pattern=""): """Return space available on *nix system (BSD/Linux).""" self.ssh_ctl_chan._enter_shell() remote_cmd = "/bin/df -k {}".format(self.file_system) remote_output = self.ssh_ctl_chan.send_command( remote_cmd, expect_string...
Verify sufficient space is available on destination file system (return boolean).
def verify_space_available(self, search_pattern=r"(\d+) \w+ free"): """Verify sufficient space is available on destination file system (return boolean).""" if self.direction == "put": space_avail = self.remote_space_available(search_pattern=search_pattern) elif self.direction == "get...
Check if the dest_file already exists on the file system (return boolean).
def _check_file_exists_unix(self, remote_cmd=""): """Check if the dest_file already exists on the file system (return boolean).""" if self.direction == "put": self.ssh_ctl_chan._enter_shell() remote_cmd = "ls {}".format(self.file_system) remote_out = self.ssh_ctl_chan...
Get the file size of the remote file.
def remote_file_size(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" if remote_file is None: if self.direction == "put": remote_file = self.dest_file elif self.direction == "get": remote_file = self.source_file ...
Get the file size of the remote file.
def _remote_file_size_unix(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" if remote_file is None: if self.direction == "put": remote_file = self.dest_file elif self.direction == "get": remote_file = self.source_...
Compute MD5 hash of file.
def file_md5(self, file_name): """Compute MD5 hash of file.""" with open(file_name, "rb") as f: file_contents = f.read() file_hash = hashlib.md5(file_contents).hexdigest() return file_hash
Process the string to retrieve the MD5 hash Output from Cisco IOS (ASA is similar) .MD5 of flash:file_name Done! verify /md5 (flash:file_name) = 410db2a7015eaa42b1fe71f1bf3d59a2
def process_md5(md5_output, pattern=r"=\s+(\S+)"): """ Process the string to retrieve the MD5 hash Output from Cisco IOS (ASA is similar) .MD5 of flash:file_name Done! verify /md5 (flash:file_name) = 410db2a7015eaa42b1fe71f1bf3d59a2 """ match = re.search(pattern,...
Compare md5 of file on network device to md5 of local file.
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) ...
SCP transfer file.
def transfer_file(self): """SCP transfer file.""" if self.direction == "put": self.put_file() elif self.direction == "get": self.get_file()
SCP copy the file from the local system to the remote device.
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) se...
Disable SCP on remote device. Defaults to Cisco IOS command
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)
Enable SCP on remote device. Defaults to Cisco IOS command
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)
Exit configuration mode.
def exit_config_mode(self, exit_config="exit", pattern=r">"): """Exit configuration mode.""" return super(PaloAltoPanosBase, self).exit_config_mode( exit_config=exit_config, pattern=pattern )
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. Automatically enters configuration mode default: command_string = commit (device_and_network or policy_and_objects or vsys or ...
def commit( self, force=False, partial=False, device_and_network=False, policy_and_objects=False, vsys="", no_vsys=False, delay_factor=0.1, ): """ Commit the candidate configuration. Commit the entered configuration. Raise an e...
Strip command_string from output string.
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)
Strip the trailing router prompt from the output.
def strip_prompt(self, a_string): """Strip the trailing router prompt from the output.""" response_list = a_string.split(self.RESPONSE_RETURN) new_response_list = [] for line in response_list: if self.base_prompt not in line: new_response_list.append(line) ...
Strip PaloAlto-specific output. PaloAlto will also put a configuration context: [edit] This method removes those lines.
def strip_context_items(self, a_string): """Strip PaloAlto-specific output. PaloAlto will also put a configuration context: [edit] This method removes those lines. """ strings_to_strip = [r"\[edit.*\]"] response_list = a_string.split(self.RESPONSE_RETURN) ...
Palo Alto requires an extra delay
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)
Gracefully exit the SSH session.
def cleanup(self): """Gracefully exit the SSH session.""" try: self.exit_config_mode() except Exception: # Always try to send 'exit' regardless of whether exit_config_mode works or not. pass self._session_log_fin = True self.write_channel("exit...
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(CoriantSSH, self).set_base_prompt( pri_prompt_terminator=pri_prompt_terminator, ...
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(CiscoIosBase, self).check_config_mode( check_string=check_string...
Saves Config Using Copy Run Start
def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Saves Config Using Copy Run Start""" return super(CiscoIosBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
When using put inside a TCL {} section the newline is considered a new TCL statement and causes a missing curly-brace message. Convert "\n" to "\r". TCL will convert the "\r" to a "\n" i.e. you will see a "\n" inside the file on the Cisco IOS device.
def _tcl_newline_rationalize(tcl_string): """ When using put inside a TCL {} section the newline is considered a new TCL statement and causes a missing curly-brace message. Convert "\n" to "\r". TCL will convert the "\r" to a "\n" i.e. you will see a "\n" inside the file on the C...
Compute MD5 hash of file.
def file_md5(self, file_name): """Compute MD5 hash of file.""" file_contents = self._read_file(file_name) file_contents = file_contents + "\n" # Cisco IOS automatically adds this file_contents = file_contents.encode("UTF-8") return hashlib.md5(file_contents).hexdigest()
Compute MD5 hash of file.
def config_md5(self, source_config): """Compute MD5 hash of file.""" file_contents = source_config + "\n" # Cisco IOS automatically adds this file_contents = file_contents.encode("UTF-8") return hashlib.md5(file_contents).hexdigest()
Prepare the session after the connection has been established. Extra time to read HP banners.
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 yo...
Exit config mode.
def exit_config_mode(self, exit_config="return", pattern=r">"): """Exit config mode.""" return super(HPComwareBase, self).exit_config_mode( exit_config=exit_config, pattern=pattern )
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 Comware this will be the router prompt with < > or [ ] stripped off. This will be set on logging in, but not when enteri...
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 Comwar...
Save Config.
def save_config(self, cmd="save force", confirm=False, confirm_response=""): """Save Config.""" return super(HPComwareBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
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.
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 ...
Try to send an SNMP GET operation using SNMPv2 for the specified OID. Parameters ---------- oid : str The SNMP OID that you want to get. Returns ------- string : str The string as part of the value from the OID you are trying to retrieve.
def _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...
Wrapper for generic SNMP call.
def _get_snmp(self, oid): """Wrapper for generic SNMP call.""" if self.snmp_version in ["v1", "v2c"]: return self._get_snmpv2c(oid) else: return self._get_snmpv3(oid)
Try to guess the device_type using SNMP GET based on the SNMP_MAPPER dict. The type which is returned is directly matching the name in *netmiko.ssh_dispatcher.CLASS_MAPPER_BASE* dict. Thus you can use this name to retrieve automatically the right ConnectionClass Returns -------...
def autodetect(self): """ Try to guess the device_type using SNMP GET based on the SNMP_MAPPER dict. The type which is returned is directly matching the name in *netmiko.ssh_dispatcher.CLASS_MAPPER_BASE* dict. Thus you can use this name to retrieve automatically the right Connec...
Check if at shell prompt root@ and go into CLI.
def enter_cli_mode(self): """Check if at shell prompt root@ and go into CLI.""" delay_factor = self.select_delay_factor(delay_factor=0) count = 0 cur_prompt = "" while count < 50: self.write_channel(self.RETURN) time.sleep(0.1 * delay_factor) c...
Exit configuration mode.
def exit_config_mode(self, exit_config="exit configuration-mode"): """Exit configuration mode.""" output = "" if self.check_config_mode(): output = self.send_command_timing( exit_config, strip_prompt=False, strip_command=False ) # if 'Exit with...
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. Automatically enters configuration mode default: command_string = commit check and (confirm or confirm_dely or comment): Exc...
def commit( self, confirm=False, confirm_delay=None, check=False, comment="", and_quit=False, delay_factor=1, ): """ Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if...
Strip the trailing router prompt from the output.
def strip_prompt(self, *args, **kwargs): """Strip the trailing router prompt from the output.""" a_string = super(FlexvnfSSH, self).strip_prompt(*args, **kwargs) return self.strip_context_items(a_string)
Enter enable mode. With RADIUS can prompt for User Name SSH@Lab-ICX7250>en User Name:service_netmiko Password: SSH@Lab-ICX7250#
def enable( self, cmd="enable", pattern=r"(ssword|User Name)", re_flags=re.IGNORECASE ): """Enter enable mode. With RADIUS can prompt for User Name SSH@Lab-ICX7250>en User Name:service_netmiko Password: SSH@Lab-ICX7250# """ output = "" ...
Saves configuration.
def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Saves configuration.""" return super(RuckusFastironBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Ruckus FastIron/ICX does not always echo commands to output by default. If server expresses interest in 'ECHO' option, then reply back with 'DO ECHO'
def _process_option(self, tsocket, command, option): """ Ruckus FastIron/ICX does not always echo commands to output by default. If server expresses interest in 'ECHO' option, then reply back with 'DO ECHO' """ if option == ECHO: tsocket.sendall(IAC + DO + ECH...
Use Netmiko to execute show version. Use a queue to pass the data back to the main process.
def show_version_queue(a_device, output_q): """ Use Netmiko to execute show version. Use a queue to pass the data back to the main process. """ output_dict = {} remote_conn = ConnectHandler(**a_device) hostname = remote_conn.base_prompt output = ("#" * 80) + "\n" output += remote_con...
Use processes and Netmiko to connect to each of the devices. Execute 'show version' on each device. Use a queue to pass the output back to the parent process. Record the amount of time required to do this.
def main(): """ Use processes and Netmiko to connect to each of the devices. Execute 'show 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) proc...
Prepare the session after the connection has been established.
def session_preparation(self): """Prepare the session after the connection has been established.""" self._test_channel_read() self.set_base_prompt() if self.secret: self.enable() else: self.asa_login() self.disable_paging(command="terminal pager 0"...
If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change.
def send_command_timing(self, *args, **kwargs): """ If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change. """ output = super(CiscoAsaSSH, self).send_command_timing(*args, **kwargs) if len(args) >= 1: command_s...
If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change.
def send_command(self, *args, **kwargs): """ If the ASA is in multi-context mode, then the base_prompt needs to be updated after each context change. """ if len(args) >= 1: command_string = args[0] else: command_string = kwargs["command_string"] ...
Cisco ASA in multi-context mode needs to have the base prompt updated (if you switch contexts i.e. 'changeto') This switch of ASA contexts can occur in configuration mode. If this happens the trailing '(config*' needs stripped off.
def set_base_prompt(self, *args, **kwargs): """ Cisco ASA in multi-context mode needs to have the base prompt updated (if you switch contexts i.e. 'changeto') This switch of ASA contexts can occur in configuration mode. If this happens the trailing '(config*' needs stripped off....
Handle ASA reaching privilege level 15 using login twb-dc-fw1> login Username: admin Password: ************
def asa_login(self): """ Handle ASA reaching privilege level 15 using login twb-dc-fw1> login Username: admin Password: ************ """ delay_factor = self.select_delay_factor(0) i = 1 max_attempts = 50 self.write_channel("login" + self....
Saves Config
def save_config(self, cmd="write mem", confirm=False, confirm_response=""): """Saves Config""" return super(CiscoAsaSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
IOS-XR requires you not exit from configuration mode.
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """IOS-XR requires you not exit from configuration mode.""" return super(CiscoXrSSH, self).send_config_set( config_commands=config_commands, exit_config_mode=False, **kwargs )
Commit the candidate configuration. default (no options): command_string = commit confirm and confirm_delay: command_string = commit confirmed <confirm_delay> label (which is a label name): command_string = commit label <label> comment: co...
def commit( self, confirm=False, confirm_delay=None, comment="", label="", delay_factor=1 ): """ Commit the candidate configuration. default (no options): command_string = commit confirm and confirm_delay: command_string = commit confirmed <confirm_de...
Checks if the device is in configuration mode or not. IOS-XR, unfortunately, does this: RP/0/RSP0/CPU0:BNG(admin)#
def check_config_mode(self, check_string=")#", pattern=r"[#\$]"): """Checks if the device is in configuration mode or not. IOS-XR, unfortunately, does this: RP/0/RSP0/CPU0:BNG(admin)# """ self.write_channel(self.RETURN) output = self.read_until_pattern(pattern=pattern) ...
IOS-XR defaults with timestamps enabled # show md5 file /bootflash:/boot/grub/grub.cfg Sat Mar 3 17:49:03.596 UTC c84843f0030efd44b01343fdb8c2e801
def process_md5(self, md5_output, pattern=r"^([a-fA-F0-9]+)$"): """ IOS-XR defaults with timestamps enabled # show md5 file /bootflash:/boot/grub/grub.cfg Sat Mar 3 17:49:03.596 UTC c84843f0030efd44b01343fdb8c2e801 """ match = re.search(pattern, md5_output, flag...
Saves Config
def save_config( self, cmd="copy running-configuration startup-configuration", confirm=False, confirm_response="", ): """Saves Config""" return super(DellOS10SSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Get the file size of the remote file.
def remote_file_size(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" if remote_file is None: if self.direction == "put": remote_file = self.dest_file elif self.direction == "get": remote_file = self.source_file ...
Return space available on remote device.
def remote_space_available(self, search_pattern=r"(\d+) bytes free"): """Return space available on remote device.""" remote_cmd = 'system "df {}"'.format(self.folder_name) remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd) for line in remote_output.splitlines(): ...
Check if the dest_file already exists on the file system (return boolean).
def check_file_exists(self, remote_cmd="dir home"): """Check if the dest_file already exists on the file system (return boolean).""" if self.direction == "put": remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd) search_string = r"Directory contents .*{}".format(self.d...
SCP copy the file from the remote device to local system.
def get_file(self): """SCP copy the file from the remote device to local system.""" source_file = "{}".format(self.source_file) self.scp_conn.scp_get_file(source_file, self.dest_file) self.scp_conn.close()