text
stringlengths
81
112k
Normalize CLI commands to have a single trailing newline. :param command: Command that may require line feed to be normalized :type command: str def normalize_cmd(self, command): """Normalize CLI commands to have a single trailing newline. :param command: Command that may require line...
Check if in enable mode. Return boolean. :param check_string: Identification of privilege mode from device :type check_string: str def check_enable_mode(self, check_string=""): """Check if in enable mode. Return boolean. :param check_string: Identification of privilege mode from devic...
Enter enable mode. :param cmd: Device command to enter enable mode :type cmd: str :param pattern: pattern to search for indicating device is waiting for password :type pattern: str :param re_flags: Regular expression flags used in conjunction with pattern :type re_flag...
Exit enable mode. :param exit_command: Command that exits the session from privileged mode :type exit_command: str def exit_enable_mode(self, exit_command=""): """Exit enable mode. :param exit_command: Command that exits the session from privileged mode :type exit_command: str...
Checks if the device is in configuration mode or not. :param check_string: Identification of configuration mode from the device :type check_string: str :param pattern: Pattern to terminate reading of channel :type pattern: str def check_config_mode(self, check_string="", pattern=""): ...
Enter into config_mode. :param config_command: Configuration command to send to the device :type config_command: str :param pattern: Pattern to terminate reading of channel :type pattern: str def config_mode(self, config_command="", pattern=""): """Enter into config_mode. ...
Exit from configuration mode. :param exit_config: Command to exit configuration mode :type exit_config: str :param pattern: Pattern to terminate reading of channel :type pattern: str def exit_config_mode(self, exit_config="", pattern=""): """Exit from configuration mode. ...
Send configuration commands down the SSH channel from a file. The file is processed line-by-line and each command is sent down the SSH channel. **kwargs are passed to send_config_set method. :param config_file: Path to configuration file to be sent to the device :type config_f...
Send configuration commands down the SSH channel. config_commands is an iterable containing all of the configuration commands. The commands will be executed one after the other. Automatically exits/enters configuration mode. :param config_commands: Multiple configuration commands to b...
Remove any ANSI (VT100) ESC codes from the output http://en.wikipedia.org/wiki/ANSI_escape_code Note: this does not capture ALL possible ANSI Escape Codes only the ones I have encountered Current codes that are filtered: ESC = '\x1b' or chr(27) ESC = is the escape char...
Try to gracefully close the SSH connection. def disconnect(self): """Try to gracefully close the SSH connection.""" try: self.cleanup() if self.protocol == "ssh": self.paramiko_cleanup() elif self.protocol == "telnet": self.remote_conn...
Open the session_log file. def open_session_log(self, filename, mode="write"): """Open the session_log file.""" if mode == "append": self.session_log = open(filename, mode="ab") else: self.session_log = open(filename, mode="wb") self._session_log_close = True
Close the session_log file (if it is a file that we opened). def close_session_log(self): """Close the session_log file (if it is a file that we opened).""" if self.session_log is not None and self._session_log_close: self.session_log.close() self.session_log = None
Saves Config Using write command def save_config(self, cmd="write", confirm=False, confirm_response=""): """Saves Config Using write command""" return super(IpInfusionOcNOSBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
For all telnet options, re-implement the default telnetlib behaviour and refuse to handle any options. If the server expresses interest in 'terminal type' option, then reply back with 'xterm' terminal type. def _process_option(self, tsocket, command, option): """ For all telnet options,...
Disable paging is only available with specific roles so it may fail. def disable_paging(self, delay_factor=1): """Disable paging is only available with specific roles so it may fail.""" check_command = "get system status | grep Virtual" output = self.send_command_timing(check_command) s...
Save the state of the output mode so it can be reset at the end of the session. def _retrieve_output_mode(self): """Save the state of the output mode so it can be reset at the end of the session.""" reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n") output = self.send_command("get system ...
Re-enable paging globally. def cleanup(self): """Re-enable paging globally.""" if self.allow_disable_global: # Return paging state output_mode_cmd = "set output {}".format(self._output_mode) enable_paging_commands = ["config system console", output_mode_cmd, "end"] ...
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(AccedianSS...
Prepare the session after the connection has been established. Procurve uses - 'Press any key to continue' def session_preparation(self): """ Prepare the session after the connection has been established. Procurve uses - 'Press any key to continue' """ delay_factor = sel...
Enter enable mode def enable( self, cmd="enable", pattern="password", re_flags=re.IGNORECASE, default_username="manager", ): """Enter enable mode""" if self.check_enable_mode(): return "" output = self.send_command_timing(cmd) if (...
Gracefully exit the SSH session. def cleanup(self): """Gracefully exit the SSH session.""" self.exit_config_mode() self.write_channel("logout" + self.RETURN) count = 0 while count <= 5: time.sleep(0.5) output = self.read_channel() if "Do you w...
Save Config. def save_config(self, cmd="write memory", confirm=False, confirm_response=""): """Save Config.""" return super(HPProcurveBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Telnet login: can be username/password or just password. def telnet_login( self, pri_prompt_terminator="#", alt_prompt_terminator=">", username_pattern=r"Login Name:", pwd_pattern=r"assword", delay_factor=1, max_loops=60, ): """Telnet login: can be us...
Prepare the session after the connection has been established. def session_preparation(self): """Prepare the session after the connection has been established.""" self._test_channel_read() self.set_base_prompt() self.tmsh_mode() self.set_base_prompt() self.disable_paging...
tmsh command is equivalent to config command on F5. def tmsh_mode(self, delay_factor=1): """tmsh command is equivalent to config command on F5.""" delay_factor = self.select_delay_factor(delay_factor) self.clear_buffer() command = "{}tmsh{}".format(self.RETURN, self.RETURN) self...
Determine base prompt. def set_base_prompt( self, pri_prompt_terminator="$", alt_prompt_terminator="#", delay_factor=1 ): """Determine base prompt.""" return super(LinuxSSH, self).set_base_prompt( pri_prompt_terminator=pri_prompt_terminator, alt_prompt_terminator=alt...
Can't exit from root (if root) def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs): """Can't exit from root (if root)""" if self.username == "root": exit_config_mode = False return super(LinuxSSH, self).send_config_set( config_commands=config...
Exit enable mode. def exit_enable_mode(self, exit_command="exit"): """Exit enable mode.""" delay_factor = self.select_delay_factor(delay_factor=0) output = "" if self.check_enable_mode(): self.write_channel(self.normalize_cmd(exit_command)) time.sleep(0.3 * delay...
Attempt to become root. def enable(self, cmd="sudo su", pattern="ssword", re_flags=re.IGNORECASE): """Attempt to become root.""" delay_factor = self.select_delay_factor(delay_factor=0) output = "" if not self.check_enable_mode(): self.write_channel(self.normalize_cmd(cmd)) ...
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.""" return self._remote_file_size_unix( remote_cmd=remote_cmd, remote_file=remote_file )
Use Secure Copy or Inline (IOS-only) to transfer files to/from network devices. inline_transfer ONLY SUPPORTS TEXT FILES and will not support binary file transfers. return { 'file_exists': boolean, 'file_transferred': boolean, 'file_verified': boolean, } def file_transfer( ssh...
Remove the > when navigating into the different config level. 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...
Enter enable mode. def enable(self, cmd="enable-admin", pattern="ssword", re_flags=re.IGNORECASE): """Enter enable mode.""" return super(AlcatelSrosSSH, self).enable( cmd=cmd, pattern=pattern, re_flags=re_flags )
Check whether we are in enable-admin mode. SROS requires us to do this: *A:HOSTNAME# enable-admin MINOR: CLI Already in admin mode. *A:HOSTNAME# *A:HOSTNAME# enable-admin Password: MINOR: CLI Invalid password. *A:HOSTNAME# def check_enable_mode(self, che...
Enter into configuration mode on SROS device. 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 )
Exit from configuration mode. def exit_config_mode(self, exit_config="exit all", pattern="#"): """ Exit from configuration mode.""" return super(AlcatelSrosSSH, self).exit_config_mode( exit_config=exit_config, pattern=pattern )
Checks if the device is in configuration mode or not. def check_config_mode(self, check_string="config", pattern="#"): """ Checks if the device is in configuration mode or not. """ return super(AlcatelSrosSSH, self).check_config_mode( check_string=check_string, pattern=pattern )
Saves Config def save_config( self, cmd="copy running-configuration startup-configuration", confirm=False, confirm_response="", ): """Saves Config""" return super(DellDNOS6Base, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_respons...
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. ...
Extreme needs special handler here due to the prompt changes. 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...
Saves configuration. def save_config( self, cmd="save configuration primary", confirm=False, confirm_response="" ): """Saves configuration.""" return super(ExtremeExosBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
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) ...
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(JuniperBase, self).strip_prompt(*args, **kwargs) return self.strip_context_items(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. def strip_context_items(self, a_string): """Strip Juniper-specific output. Juniper will ...
Checks if the device is in configuration mode or not. Arista, unfortunately, does this: loc1-core01(s1)# Can also be (s2) def check_config_mode(self, check_string=")#", pattern=""): """ Checks if the device is in configuration mode or not. Arista, unfortunately, does ...
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(pattern=r"[>#]") self.ansi_escape_codes = True self.set_base_prompt() self.disable_paging() ...
Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text. 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> pattern...
Checks if the device is in configuration mode or not. def check_config_mode(self, check_string=")#", pattern="#"): """Checks if the device is in configuration mode or not.""" return super(CiscoNxosSSH, self).check_config_mode( check_string=check_string, pattern=pattern )
Check if the dest_file already exists on the file system (return boolean). def check_file_exists(self, remote_cmd=""): """Check if the dest_file already exists on the file system (return boolean).""" if self.direction == "put": if not remote_cmd: remote_cmd = "dir {}{}".form...
Strip the trailing router prompt from the output. def strip_prompt(self, a_string): """Strip the trailing router prompt from the output.""" expect_string = r"^(OK|ERROR|Command not recognized\.)$" response_list = a_string.split(self.RESPONSE_RETURN) last_line = response_list[-1] ...
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 ...
Save Config for Extreme VDX. def save_config( self, cmd="copy running-config startup-config", confirm=True, confirm_response="y", ): """Save Config for Extreme VDX.""" return super(ExtremeNosSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_respon...
Exit configuration mode. def exit_config_mode(self, exit_config="return", pattern=r">"): """Exit configuration mode.""" return super(HuaweiBase, 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...
Save Config for HuaweiSSH def save_config(self, cmd="save", confirm=False, confirm_response=""): """ Save Config for HuaweiSSH""" return super(HuaweiBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Telnet login for Huawei Devices def telnet_login( self, pri_prompt_terminator=r"]\s*$", alt_prompt_terminator=r">\s*$", username_pattern=r"(?:user:|username|login|user name)", pwd_pattern=r"assword", delay_factor=1, max_loops=20, ): """Telnet login fo...
Commit the candidate configuration. Commit the entered configuration. Raise an error and return the failure if the commit fails. default: command_string = commit comment: command_string = commit comment <comment> def commit(self, comment="", delay_factor=1): ...
Enable/disable SCP on Cisco ASA. def asa_scp_handler(ssh_conn, cmd="ssh scopy enable", mode="enable"): """Enable/disable SCP on Cisco ASA.""" if mode == "disable": cmd = "no " + cmd return ssh_conn.send_config_set([cmd])
Script to upgrade a Cisco ASA. def main(): """Script to upgrade a Cisco ASA.""" try: ip_addr = raw_input("Enter ASA IP address: ") except NameError: ip_addr = input("Enter ASA IP address: ") my_pass = getpass() start_time = datetime.now() print(">>>> {}".format(start_time)) ...
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("show version")) print("#" * 80) print()
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. 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...
WLC presents with the following on login (in certain OS versions) login as: user (Cisco Controller) User: user Password:**** def special_login_handler(self, delay_factor=1): """WLC presents with the following on login (in certain OS versions) login as: user ...
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message Even though pagination is disabled show run-config also has excessive delays in the output which requires special handling. Arguments are the same as send_command_timing() method def send_command_w_enter(self, *...
Checks if the device is in configuration mode or not. def check_config_mode(self, check_string="config", pattern=""): """Checks if the device is in configuration mode or not.""" if not pattern: pattern = re.escape(self.base_prompt) return super(CiscoWlcSSH, self).check_config_mode(c...
Exit config_mode. def exit_config_mode(self, exit_config="exit", pattern=""): """Exit config_mode.""" if not pattern: pattern = re.escape(self.base_prompt) return super(CiscoWlcSSH, self).exit_config_mode(exit_config, pattern)
Saves Config. def save_config(self, cmd="save config", confirm=True, confirm_response="y"): """Saves Config.""" self.enable() if confirm: output = self.send_command_timing(command_string=cmd) if confirm_response: output += self.send_command_timing(confirm...
Recreate the key index. def _BuildIndex(self): """Recreate the key index.""" self._index = {} for i, k in enumerate(self._keys): self._index[k] = i
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. def ge...
Fetches the column number (0 indexed). Args: column: A string, column to fetch the index of. Returns: An int, the row index number. Raises: ValueError: The specified column was not found. def index(self, column): # pylint: disable=C6409 """Fetches the column number (0 indexed)...
Sets row's colour attributes to a list of values in terminal.SGR. 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: ...
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. def Insert(self, key, value, row_index): """Inserts new values at a specified o...
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(). def Map(self, function): """...
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 sort(self, cmp=None, key=None, reverse=False): """Sorts rows in the texttable. Args: cmp: func, non def...
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...
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. def Remove(self, row): """Removes a row from the table. Args: row: int, the row number...
Returns the current row as a tuple. 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(...
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. def _SetRow(self, new_values, row=0): """Sets the current row to new list. ...
Sets header of table to the given tuple. Args: new_values: Tuple of new header values. 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 ne...
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. def _SmallestColSize(se...
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...
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. def AddColumn(self, column, default="", co...
Adds a new row (list) to the table. Args: new_values: Tuple, dict, or Row() of new values to append as a row. Raises: TableError: Supplied tuple not equal to table width. def Append(self, new_values): """Adds a new row (list) to the table. Args: new_values: Tuple, dict, or Row(...
Fetches a new, empty row, with headers populated. Args: value: Initial value to set each row entry to. Returns: A Row() object. def NewRow(self, value=""): """Fetches a new, empty row, with headers populated. Args: value: Initial value to set each row entry to. Returns: ...
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: ...
Save Config def save_config(self, cmd="save config", confirm=False, confirm_response=""): """Save Config""" return super(ExtremeVspSSH, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Make sure paging is disabled. 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 )
Read YAML file. def load_yaml_file(yaml_file): """Read YAML file.""" try: import yaml except ImportError: sys.exit("Unable to import yaml module.") try: with io.open(yaml_file, "rt", encoding="utf-8") as fname: return yaml.safe_load(fname) except IOError: ...
Look for .netmiko.yml in current dir, then ~/.netmiko.yml. def find_cfg_file(file_name=None): """Look for .netmiko.yml in current dir, then ~/.netmiko.yml.""" base_file = ".netmiko.yml" check_files = [base_file, os.path.expanduser("~") + "/" + base_file] if file_name: check_files.insert(0, file...
Print out inventory devices and groups. 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, di...
Dynamically create 'all' group. 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_gro...
Ensure directory exists. Create if necessary. 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): ...
Check environment first, then default dir def find_netmiko_dir(): """Check environment first, then default dir""" try: netmiko_base_dir = os.environ["NETMIKO_DIR"] except KeyError: netmiko_base_dir = NETMIKO_BASE_DIR netmiko_base_dir = os.path.expanduser(netmiko_base_dir) if netmiko...
Write Python2 and Python3 compatible byte stream. 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") ...
returns valid COM Port. def check_serial_port(name): """returns valid COM Port.""" try: cdc = next(serial.tools.list_ports.grep(name)) return cdc[0] except StopIteration: msg = "device {} not found. ".format(name) msg += "available devices are: " ports = list(serial....
Find and return the ntc-templates/templates dir. def get_template_dir(): """Find and return the ntc-templates/templates dir.""" try: template_dir = os.path.expanduser(os.environ["NET_TEXTFSM"]) index = os.path.join(template_dir, "index") if not os.path.isfile(index): # Assum...
Converts TextFSM cli_table object to list of dictionaries. def clitable_to_dict(cli_table): """Converts TextFSM cli_table object to list of dictionaries.""" objs = [] for row in cli_table: temp_dict = {} for index, element in enumerate(row): temp_dict[cli_table.header[index].low...
Convert raw CLI output to structured data using TextFSM template. def get_structured_data(raw_output, platform, command): """Convert raw CLI output to structured data using TextFSM template.""" template_dir = get_template_dir() index_file = os.path.join(template_dir, "index") textfsm_obj = clitable.Cli...
Save Config def save_config(self, cmd="write memory", confirm=False, confirm_response=""): """Save Config""" return super(ExtremeNetironBase, self).save_config( cmd=cmd, confirm=confirm, confirm_response=confirm_response )
Create a ElastiCache Redis Node and EC2 Instance def main(): """ Create a ElastiCache Redis Node and EC2 Instance """ template = Template() # Description template.add_description( 'AWS CloudFormation Sample Template ElastiCache_Redis:' 'Sample template showing how to create an...