diff --git a/docs/netmiko/arista/arista.html b/docs/netmiko/arista/arista.html index a426d43ad..02f218488 100644 --- a/docs/netmiko/arista/arista.html +++ b/docs/netmiko/arista/arista.html @@ -22,21 +22,24 @@

Module netmiko.arista.arista

Source code -
import time
+
import re
 from netmiko.cisco_base_connection import CiscoSSHConnection
 from netmiko.cisco_base_connection import CiscoFileTransfer
 
 
 class AristaBase(CiscoSSHConnection):
+    def __init__(self, *args, **kwargs):
+        kwargs.setdefault("fast_cli", True)
+        kwargs.setdefault("_legacy_mode", False)
+        return super().__init__(*args, **kwargs)
+
     def session_preparation(self):
         """Prepare the session after the connection has been established."""
-        self._test_channel_read(pattern=r"[>#]")
+        cmd = "terminal width 511"
+        # Arista will echo immediately and then when the device really responds (like NX-OS)
+        self.set_terminal_width(command=cmd, pattern=r"Width set to")
+        self.disable_paging(cmd_verify=False, pattern=r"Pagination disabled")
         self.set_base_prompt()
-        self.set_terminal_width(command="terminal width 511", pattern="terminal")
-        self.disable_paging()
-        # Clear the read buffer
-        time.sleep(0.3 * self.global_delay_factor)
-        self.clear_buffer()
 
     def check_config_mode(self, check_string=")#", pattern=""):
         """
@@ -57,6 +60,20 @@ 

Module netmiko.arista.arista

output = output.replace("(s2)", "") return check_string in output + def config_mode(self, config_command="configure terminal", pattern="", re_flags=0): + """Force arista to read pattern all the way to prompt on the next line.""" + + if not re_flags: + re_flags = re.DOTALL + check_string = re.escape(")#") + + if not pattern: + pattern = re.escape(self.base_prompt[:16]) + pattern = f"{pattern}.*{check_string}" + return super().config_mode( + config_command=config_command, pattern=pattern, re_flags=re_flags + ) + def _enter_shell(self): """Enter the Bourne Shell.""" return self.send_command("bash", expect_string=r"[\$#]") @@ -143,7 +160,7 @@

Classes

class AristaBase -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

Base Class for cisco-like behavior.

@@ -280,15 +297,18 @@

Classes

Source code
class AristaBase(CiscoSSHConnection):
+    def __init__(self, *args, **kwargs):
+        kwargs.setdefault("fast_cli", True)
+        kwargs.setdefault("_legacy_mode", False)
+        return super().__init__(*args, **kwargs)
+
     def session_preparation(self):
         """Prepare the session after the connection has been established."""
-        self._test_channel_read(pattern=r"[>#]")
+        cmd = "terminal width 511"
+        # Arista will echo immediately and then when the device really responds (like NX-OS)
+        self.set_terminal_width(command=cmd, pattern=r"Width set to")
+        self.disable_paging(cmd_verify=False, pattern=r"Pagination disabled")
         self.set_base_prompt()
-        self.set_terminal_width(command="terminal width 511", pattern="terminal")
-        self.disable_paging()
-        # Clear the read buffer
-        time.sleep(0.3 * self.global_delay_factor)
-        self.clear_buffer()
 
     def check_config_mode(self, check_string=")#", pattern=""):
         """
@@ -309,6 +329,20 @@ 

Classes

output = output.replace("(s2)", "") return check_string in output + def config_mode(self, config_command="configure terminal", pattern="", re_flags=0): + """Force arista to read pattern all the way to prompt on the next line.""" + + if not re_flags: + re_flags = re.DOTALL + check_string = re.escape(")#") + + if not pattern: + pattern = re.escape(self.base_prompt[:16]) + pattern = f"{pattern}.*{check_string}" + return super().config_mode( + config_command=config_command, pattern=pattern, re_flags=re_flags + ) + def _enter_shell(self): """Enter the Bourne Shell.""" return self.send_command("bash", expect_string=r"[\$#]") @@ -360,6 +394,28 @@

Methods

return check_string in output
+
+def config_mode(self, config_command='configure terminal', pattern='', re_flags=0) +
+
+

Force arista to read pattern all the way to prompt on the next line.

+
+Source code +
def config_mode(self, config_command="configure terminal", pattern="", re_flags=0):
+    """Force arista to read pattern all the way to prompt on the next line."""
+
+    if not re_flags:
+        re_flags = re.DOTALL
+    check_string = re.escape(")#")
+
+    if not pattern:
+        pattern = re.escape(self.base_prompt[:16])
+        pattern = f"{pattern}.*{check_string}"
+    return super().config_mode(
+        config_command=config_command, pattern=pattern, re_flags=re_flags
+    )
+
+
def session_preparation(self)
@@ -369,13 +425,11 @@

Methods

Source code
def session_preparation(self):
     """Prepare the session after the connection has been established."""
-    self._test_channel_read(pattern=r"[>#]")
-    self.set_base_prompt()
-    self.set_terminal_width(command="terminal width 511", pattern="terminal")
-    self.disable_paging()
-    # Clear the read buffer
-    time.sleep(0.3 * self.global_delay_factor)
-    self.clear_buffer()
+ cmd = "terminal width 511" + # Arista will echo immediately and then when the device really responds (like NX-OS) + self.set_terminal_width(command=cmd, pattern=r"Width set to") + self.disable_paging(cmd_verify=False, pattern=r"Pagination disabled") + self.set_base_prompt()
@@ -388,7 +442,6 @@

Inherited members

  • clear_buffer
  • close_session_log
  • commit
  • -
  • config_mode
  • disable_paging
  • disconnect
  • enable
  • @@ -519,7 +572,7 @@

    Inherited members

    class AristaSSH -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Base Class for cisco-like behavior.

    @@ -675,7 +728,7 @@

    Inherited members

  • clear_buffer
  • close_session_log
  • commit
  • -
  • config_mode
  • +
  • config_mode
  • disable_paging
  • disconnect
  • enable
  • @@ -874,7 +927,7 @@

    Inherited members

  • clear_buffer
  • close_session_log
  • commit
  • -
  • config_mode
  • +
  • config_mode
  • disable_paging
  • disconnect
  • enable
  • @@ -932,6 +985,7 @@

    Index

    AristaBase

    diff --git a/docs/netmiko/arista/index.html b/docs/netmiko/arista/index.html index e5e8d4f77..f68d8cd46 100644 --- a/docs/netmiko/arista/index.html +++ b/docs/netmiko/arista/index.html @@ -137,7 +137,7 @@

    Inherited members

    class AristaSSH -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Base Class for cisco-like behavior.

    @@ -293,7 +293,7 @@

    Inherited members

  • clear_buffer
  • close_session_log
  • commit
  • -
  • config_mode
  • +
  • config_mode
  • disable_paging
  • disconnect
  • enable
  • @@ -492,7 +492,7 @@

    Inherited members

  • clear_buffer
  • close_session_log
  • commit
  • -
  • config_mode
  • +
  • config_mode
  • disable_paging
  • disconnect
  • enable
  • diff --git a/docs/netmiko/aruba/aruba_ssh.html b/docs/netmiko/aruba/aruba_ssh.html index 1a254b0c3..4ff52af1d 100644 --- a/docs/netmiko/aruba/aruba_ssh.html +++ b/docs/netmiko/aruba/aruba_ssh.html @@ -5,7 +5,7 @@ netmiko.aruba.aruba_ssh API documentation - + @@ -20,10 +20,16 @@

    Module netmiko.aruba.aruba_ssh

    -

    Aruba OS support

    +

    Aruba OS support.

    +

    For use with Aruba OS Controllers.

    Source code -
    """Aruba OS support"""
    +
    """
    +Aruba OS support.
    +
    +For use with Aruba OS Controllers.
    +
    +"""
     import time
     import re
     from netmiko.cisco_base_connection import CiscoSSHConnection
    diff --git a/docs/netmiko/aruba/index.html b/docs/netmiko/aruba/index.html
    index b8076d60d..7b5031e92 100644
    --- a/docs/netmiko/aruba/index.html
    +++ b/docs/netmiko/aruba/index.html
    @@ -32,7 +32,7 @@ 

    Sub-modules

    netmiko.aruba.aruba_ssh
    -

    Aruba OS support

    +

    Aruba OS support …

    diff --git a/docs/netmiko/base_connection.html b/docs/netmiko/base_connection.html index 8ddfbbba0..890587101 100644 --- a/docs/netmiko/base_connection.html +++ b/docs/netmiko/base_connection.html @@ -45,6 +45,7 @@

    Module netmiko.base_connection

    import paramiko import serial +from tenacity import retry, stop_after_attempt, wait_exponential from netmiko import log from netmiko.netmiko_globals import MAX_BUFFER, BACKSPACE_CHAR @@ -57,6 +58,7 @@

    Module netmiko.base_connection

    check_serial_port, get_structured_data, get_structured_data_genie, + get_structured_data_ttp, select_cmd_verify, ) from netmiko.utilities import m_exec_time # noqa @@ -1008,6 +1010,7 @@

    Module netmiko.base_connection

    print("Interactive SSH session established") return "" + # @m_exec_time def _test_channel_read(self, count=40, pattern=""): """Try to read the channel (generally post login) verify you receive data back. @@ -1039,6 +1042,7 @@

    Module netmiko.base_connection

    break else: self.write_channel(self.RETURN) + main_delay = _increment_delay(main_delay) time.sleep(main_delay) i += 1 @@ -1073,7 +1077,7 @@

    Module netmiko.base_connection

    :type delay_factor: int """ if self.fast_cli: - if delay_factor <= self.global_delay_factor: + if delay_factor and delay_factor <= self.global_delay_factor: return delay_factor else: return self.global_delay_factor @@ -1142,6 +1146,10 @@

    Module netmiko.base_connection

    output = self.read_until_prompt() return output + # Retry by sleeping .33 and then double sleep until 5 attempts (.33, .66, 1.32, etc) + @retry( + wait=wait_exponential(multiplier=0.33, min=0, max=5), stop=stop_after_attempt(5) + ) def set_base_prompt( self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1 ): @@ -1236,6 +1244,8 @@

    Module netmiko.base_connection

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=False, cmd_echo=None, @@ -1269,6 +1279,13 @@

    Module netmiko.base_connection

    path, relative path, or name of file in current directory. (default: None). :type textfsm_template: str + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type use_genie: bool @@ -1278,13 +1295,19 @@

    Module netmiko.base_connection

    :param cmd_echo: Deprecated (use cmd_verify instead) :type cmd_echo: bool """ - # For compatibility remove cmd_echo in Netmiko 4.x.x + + # For compatibility; remove cmd_echo in Netmiko 4.x.x if cmd_echo is not None: cmd_verify = cmd_echo output = "" + delay_factor = self.select_delay_factor(delay_factor) - self.clear_buffer() + # Cleanup in future versions of Netmiko + if delay_factor < 1: + if not self._legacy_mode and self.fast_cli: + delay_factor = 1 + if normalize: command_string = self.normalize_cmd(command_string) @@ -1319,7 +1342,7 @@

    Module netmiko.base_connection

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -1330,6 +1353,11 @@

    Module netmiko.base_connection

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -1394,6 +1422,8 @@

    Module netmiko.base_connection

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=True, ): @@ -1431,6 +1461,13 @@

    Module netmiko.base_connection

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None). + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type normalize: bool @@ -1512,7 +1549,7 @@

    Module netmiko.base_connection

    new_data = self.read_channel() else: # nobreak raise IOError( - "Search pattern never detected in send_command_expect: {}".format( + "Search pattern never detected in send_command: {}".format( search_pattern ) ) @@ -1524,7 +1561,7 @@

    Module netmiko.base_connection

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -1535,6 +1572,11 @@

    Module netmiko.base_connection

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -1691,7 +1733,7 @@

    Module netmiko.base_connection

    output = self.read_until_pattern(pattern=pattern) return check_string in output - def config_mode(self, config_command="", pattern=""): + def config_mode(self, config_command="", pattern="", re_flags=0): """Enter into config_mode. :param config_command: Configuration command to send to the device @@ -1699,6 +1741,9 @@

    Module netmiko.base_connection

    :param pattern: Pattern to terminate reading of channel :type pattern: str + + :param re_flags: Regular expression flags + :type re_flags: RegexFlag """ output = "" if not self.check_config_mode(): @@ -1708,8 +1753,8 @@

    Module netmiko.base_connection

    output += self.read_until_pattern( pattern=re.escape(config_command.strip()) ) - if not re.search(pattern, output, flags=re.M): - output += self.read_until_pattern(pattern=pattern) + if not re.search(pattern, output, flags=re_flags): + output += self.read_until_pattern(pattern=pattern, re_flags=re_flags) if not self.check_config_mode(): raise ValueError("Failed to enter configuration mode.") return output @@ -3102,6 +3147,7 @@

    Classes

    print("Interactive SSH session established") return "" + # @m_exec_time def _test_channel_read(self, count=40, pattern=""): """Try to read the channel (generally post login) verify you receive data back. @@ -3133,6 +3179,7 @@

    Classes

    break else: self.write_channel(self.RETURN) + main_delay = _increment_delay(main_delay) time.sleep(main_delay) i += 1 @@ -3167,7 +3214,7 @@

    Classes

    :type delay_factor: int """ if self.fast_cli: - if delay_factor <= self.global_delay_factor: + if delay_factor and delay_factor <= self.global_delay_factor: return delay_factor else: return self.global_delay_factor @@ -3236,6 +3283,10 @@

    Classes

    output = self.read_until_prompt() return output + # Retry by sleeping .33 and then double sleep until 5 attempts (.33, .66, 1.32, etc) + @retry( + wait=wait_exponential(multiplier=0.33, min=0, max=5), stop=stop_after_attempt(5) + ) def set_base_prompt( self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1 ): @@ -3330,6 +3381,8 @@

    Classes

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=False, cmd_echo=None, @@ -3363,6 +3416,13 @@

    Classes

    path, relative path, or name of file in current directory. (default: None). :type textfsm_template: str + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type use_genie: bool @@ -3372,13 +3432,19 @@

    Classes

    :param cmd_echo: Deprecated (use cmd_verify instead) :type cmd_echo: bool """ - # For compatibility remove cmd_echo in Netmiko 4.x.x + + # For compatibility; remove cmd_echo in Netmiko 4.x.x if cmd_echo is not None: cmd_verify = cmd_echo output = "" + delay_factor = self.select_delay_factor(delay_factor) - self.clear_buffer() + # Cleanup in future versions of Netmiko + if delay_factor < 1: + if not self._legacy_mode and self.fast_cli: + delay_factor = 1 + if normalize: command_string = self.normalize_cmd(command_string) @@ -3413,7 +3479,7 @@

    Classes

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -3424,6 +3490,11 @@

    Classes

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -3488,6 +3559,8 @@

    Classes

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=True, ): @@ -3525,6 +3598,13 @@

    Classes

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None). + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type normalize: bool @@ -3606,7 +3686,7 @@

    Classes

    new_data = self.read_channel() else: # nobreak raise IOError( - "Search pattern never detected in send_command_expect: {}".format( + "Search pattern never detected in send_command: {}".format( search_pattern ) ) @@ -3618,7 +3698,7 @@

    Classes

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -3629,6 +3709,11 @@

    Classes

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -3785,7 +3870,7 @@

    Classes

    output = self.read_until_pattern(pattern=pattern) return check_string in output - def config_mode(self, config_command="", pattern=""): + def config_mode(self, config_command="", pattern="", re_flags=0): """Enter into config_mode. :param config_command: Configuration command to send to the device @@ -3793,6 +3878,9 @@

    Classes

    :param pattern: Pattern to terminate reading of channel :type pattern: str + + :param re_flags: Regular expression flags + :type re_flags: RegexFlag """ output = "" if not self.check_config_mode(): @@ -3802,8 +3890,8 @@

    Classes

    output += self.read_until_pattern( pattern=re.escape(config_command.strip()) ) - if not re.search(pattern, output, flags=re.M): - output += self.read_until_pattern(pattern=pattern) + if not re.search(pattern, output, flags=re_flags): + output += self.read_until_pattern(pattern=pattern, re_flags=re_flags) if not self.check_config_mode(): raise ValueError("Failed to enter configuration mode.") return output @@ -4254,17 +4342,19 @@

    Methods

    -def config_mode(self, config_command='', pattern='') +def config_mode(self, config_command='', pattern='', re_flags=0)

    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

    +:type pattern: str

    +

    :param re_flags: Regular expression flags +:type re_flags: RegexFlag

    Source code -
    def config_mode(self, config_command="", pattern=""):
    +
    def config_mode(self, config_command="", pattern="", re_flags=0):
         """Enter into config_mode.
     
         :param config_command: Configuration command to send to the device
    @@ -4272,6 +4362,9 @@ 

    Methods

    :param pattern: Pattern to terminate reading of channel :type pattern: str + + :param re_flags: Regular expression flags + :type re_flags: RegexFlag """ output = "" if not self.check_config_mode(): @@ -4281,8 +4374,8 @@

    Methods

    output += self.read_until_pattern( pattern=re.escape(config_command.strip()) ) - if not re.search(pattern, output, flags=re.M): - output += self.read_until_pattern(pattern=pattern) + if not re.search(pattern, output, flags=re_flags): + output += self.read_until_pattern(pattern=pattern, re_flags=re_flags) if not self.check_config_mode(): raise ValueError("Failed to enter configuration mode.") return output
    @@ -4354,7 +4447,7 @@

    Methods

    -def enable(self, cmd='', pattern='ssword', re_flags=) +def enable(self, cmd='', pattern='ssword', re_flags=re.IGNORECASE)

    Enter enable mode.

    @@ -4839,7 +4932,7 @@

    Methods

    :type delay_factor: int """ if self.fast_cli: - if delay_factor <= self.global_delay_factor: + if delay_factor and delay_factor <= self.global_delay_factor: return delay_factor else: return self.global_delay_factor @@ -4851,7 +4944,7 @@

    Methods

    -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, textfsm_template=None, use_genie=False, cmd_verify=True) +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, textfsm_template=None, use_ttp=False, ttp_template=None, use_genie=False, cmd_verify=True)

    Execute command_string on the SSH channel using a pattern-based mechanism. Generally @@ -4878,6 +4971,11 @@

    Methods

    :type normalize: bool

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None).

    +

    :param use_ttp: Process command output through TTP template (default: False). +:type use_ttp: bool

    +

    :param ttp_template: Name of template to parse output with; can be fully qualified +path, relative path, or name of file in current directory. (default: None). +:type ttp_template: str

    :param use_genie: Process command output through PyATS/Genie parser (default: False). :type normalize: bool

    :param cmd_verify: Verify command echo before proceeding (default: True). @@ -4897,6 +4995,8 @@

    Methods

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=True, ): @@ -4934,6 +5034,13 @@

    Methods

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None). + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type normalize: bool @@ -5015,7 +5122,7 @@

    Methods

    new_data = self.read_channel() else: # nobreak raise IOError( - "Search pattern never detected in send_command_expect: {}".format( + "Search pattern never detected in send_command: {}".format( search_pattern ) ) @@ -5027,7 +5134,7 @@

    Methods

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -5038,6 +5145,11 @@

    Methods

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -5072,7 +5184,7 @@

    Methods

    -def send_command_timing(self, command_string, delay_factor=1, max_loops=150, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, textfsm_template=None, use_genie=False, cmd_verify=False, cmd_echo=None) +def send_command_timing(self, command_string, delay_factor=1, max_loops=150, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, textfsm_template=None, use_ttp=False, ttp_template=None, use_genie=False, cmd_verify=False, cmd_echo=None)

    Execute command_string on the SSH channel using a delay-based mechanism. Generally @@ -5095,6 +5207,11 @@

    Methods

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None). :type textfsm_template: str

    +

    :param use_ttp: Process command output through TTP template (default: False). +:type use_ttp: bool

    +

    :param ttp_template: Name of template to parse output with; can be fully qualified +path, relative path, or name of file in current directory. (default: None). +:type ttp_template: str

    :param use_genie: Process command output through PyATS/Genie parser (default: False). :type use_genie: bool

    :param cmd_verify: Verify command echo before proceeding (default: False). @@ -5114,6 +5231,8 @@

    Methods

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=False, cmd_echo=None, @@ -5147,6 +5266,13 @@

    Methods

    path, relative path, or name of file in current directory. (default: None). :type textfsm_template: str + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type use_genie: bool @@ -5156,13 +5282,19 @@

    Methods

    :param cmd_echo: Deprecated (use cmd_verify instead) :type cmd_echo: bool """ - # For compatibility remove cmd_echo in Netmiko 4.x.x + + # For compatibility; remove cmd_echo in Netmiko 4.x.x if cmd_echo is not None: cmd_verify = cmd_echo output = "" + delay_factor = self.select_delay_factor(delay_factor) - self.clear_buffer() + # Cleanup in future versions of Netmiko + if delay_factor < 1: + if not self._legacy_mode and self.fast_cli: + delay_factor = 1 + if normalize: command_string = self.normalize_cmd(command_string) @@ -5197,7 +5329,7 @@

    Methods

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -5208,6 +5340,11 @@

    Methods

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -5466,7 +5603,10 @@

    Methods

    :type delay_factor: int

    Source code -
    def set_base_prompt(
    +
    @retry(
    +    wait=wait_exponential(multiplier=0.33, min=0, max=5), stop=stop_after_attempt(5)
    +)
    +def set_base_prompt(
         self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1
     ):
         """Sets self.base_prompt
    diff --git a/docs/netmiko/cisco/cisco_ftd_ssh.html b/docs/netmiko/cisco/cisco_ftd_ssh.html
    new file mode 100644
    index 000000000..ca075cf96
    --- /dev/null
    +++ b/docs/netmiko/cisco/cisco_ftd_ssh.html
    @@ -0,0 +1,376 @@
    +
    +
    +
    +
    +
    +
    +netmiko.cisco.cisco_ftd_ssh API documentation
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Module netmiko.cisco.cisco_ftd_ssh

    +
    +
    +

    Subclass specific to Cisco FTD.

    +
    +Source code +
    """Subclass specific to Cisco FTD."""
    +from netmiko.cisco_base_connection import CiscoSSHConnection
    +
    +
    +class CiscoFtdSSH(CiscoSSHConnection):
    +    """Subclass specific to Cisco FTD."""
    +
    +    def session_preparation(self):
    +        """Prepare the session after the connection has been established."""
    +        self._test_channel_read()
    +        self.set_base_prompt()
    +
    +    def send_config_set(self, *args, **kwargs):
    +        """Canot change config on FTD via ssh"""
    +        raise NotImplementedError
    +
    +    def enable(self, *args, **kwargs):
    +        """No enable mode on firepower ssh"""
    +        return ""
    +
    +    def config_mode(self, *args, **kwargs):
    +        """No config mode on firepower ssh"""
    +        return ""
    +
    +    def check_config_mode(self, *args, **kwargs):
    +        """No config mode on firepower ssh"""
    +        return False
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class CiscoFtdSSH +(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +
    +
    +

    Subclass specific to Cisco FTD.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class CiscoFtdSSH(CiscoSSHConnection):
    +    """Subclass specific to Cisco FTD."""
    +
    +    def session_preparation(self):
    +        """Prepare the session after the connection has been established."""
    +        self._test_channel_read()
    +        self.set_base_prompt()
    +
    +    def send_config_set(self, *args, **kwargs):
    +        """Canot change config on FTD via ssh"""
    +        raise NotImplementedError
    +
    +    def enable(self, *args, **kwargs):
    +        """No enable mode on firepower ssh"""
    +        return ""
    +
    +    def config_mode(self, *args, **kwargs):
    +        """No config mode on firepower ssh"""
    +        return ""
    +
    +    def check_config_mode(self, *args, **kwargs):
    +        """No config mode on firepower ssh"""
    +        return False
    +
    +

    Ancestors

    + +

    Methods

    +
    +
    +def check_config_mode(self, *args, **kwargs) +
    +
    +

    No config mode on firepower ssh

    +
    +Source code +
    def check_config_mode(self, *args, **kwargs):
    +    """No config mode on firepower ssh"""
    +    return False
    +
    +
    +
    +def config_mode(self, *args, **kwargs) +
    +
    +

    No config mode on firepower ssh

    +
    +Source code +
    def config_mode(self, *args, **kwargs):
    +    """No config mode on firepower ssh"""
    +    return ""
    +
    +
    +
    +def enable(self, *args, **kwargs) +
    +
    +

    No enable mode on firepower ssh

    +
    +Source code +
    def enable(self, *args, **kwargs):
    +    """No enable mode on firepower ssh"""
    +    return ""
    +
    +
    +
    +def send_config_set(self, *args, **kwargs) +
    +
    +

    Canot change config on FTD via ssh

    +
    +Source code +
    def send_config_set(self, *args, **kwargs):
    +    """Canot change config on FTD via ssh"""
    +    raise NotImplementedError
    +
    +
    +
    +def session_preparation(self) +
    +
    +

    Prepare the session after the connection has been established.

    +
    +Source code +
    def session_preparation(self):
    +    """Prepare the session after the connection has been established."""
    +    self._test_channel_read()
    +    self.set_base_prompt()
    +
    +
    +
    +

    Inherited members

    + +
    +
    +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/docs/netmiko/cisco/cisco_nxos_ssh.html b/docs/netmiko/cisco/cisco_nxos_ssh.html index 64c718dbe..696572719 100644 --- a/docs/netmiko/cisco/cisco_nxos_ssh.html +++ b/docs/netmiko/cisco/cisco_nxos_ssh.html @@ -23,23 +23,28 @@

    Module netmiko.cisco.cisco_nxos_ssh

    Source code
    import re
    -import time
     import os
     from netmiko.cisco_base_connection import CiscoSSHConnection
     from netmiko.cisco_base_connection import CiscoFileTransfer
     
     
     class CiscoNxosSSH(CiscoSSHConnection):
    +    def __init__(self, *args, **kwargs):
    +        # Cisco NX-OS defaults to fast_cli=True and legacy_mode=False
    +        kwargs.setdefault("fast_cli", True)
    +        kwargs.setdefault("_legacy_mode", False)
    +        return super().__init__(*args, **kwargs)
    +
         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.set_terminal_width(command="terminal width 511", pattern="terminal")
    +        # NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_terminal_width(
    +            command="terminal width 511", pattern=r"terminal width 511"
    +        )
             self.disable_paging()
    -        # Clear the read buffer
    -        time.sleep(0.3 * self.global_delay_factor)
    -        self.clear_buffer()
    +        self.set_base_prompt()
     
         def normalize_linefeeds(self, a_string):
             """Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
    @@ -313,7 +318,7 @@ 

    Inherited members

    class CiscoNxosSSH -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Base Class for cisco-like behavior.

    @@ -450,16 +455,22 @@

    Inherited members

    Source code
    class CiscoNxosSSH(CiscoSSHConnection):
    +    def __init__(self, *args, **kwargs):
    +        # Cisco NX-OS defaults to fast_cli=True and legacy_mode=False
    +        kwargs.setdefault("fast_cli", True)
    +        kwargs.setdefault("_legacy_mode", False)
    +        return super().__init__(*args, **kwargs)
    +
         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.set_terminal_width(command="terminal width 511", pattern="terminal")
    +        # NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_terminal_width(
    +            command="terminal width 511", pattern=r"terminal width 511"
    +        )
             self.disable_paging()
    -        # Clear the read buffer
    -        time.sleep(0.3 * self.global_delay_factor)
    -        self.clear_buffer()
    +        self.set_base_prompt()
     
         def normalize_linefeeds(self, a_string):
             """Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
    @@ -518,14 +529,14 @@ 

    Methods

    Source code
    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.set_terminal_width(command="terminal width 511", pattern="terminal")
    +    # NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
    +    self._test_channel_read(pattern=r"[>#]")
    +    self.set_terminal_width(
    +        command="terminal width 511", pattern=r"terminal width 511"
    +    )
         self.disable_paging()
    -    # Clear the read buffer
    -    time.sleep(0.3 * self.global_delay_factor)
    -    self.clear_buffer()
    + self.set_base_prompt()
    diff --git a/docs/netmiko/cisco/cisco_xr.html b/docs/netmiko/cisco/cisco_xr.html index 1c35a8e30..f590b5480 100644 --- a/docs/netmiko/cisco/cisco_xr.html +++ b/docs/netmiko/cisco/cisco_xr.html @@ -22,25 +22,30 @@

    Module netmiko.cisco.cisco_xr

    Source code -
    import time
    -import re
    +
    import re
     from netmiko.cisco_base_connection import CiscoBaseConnection, CiscoFileTransfer
     
     
     class CiscoXrBase(CiscoBaseConnection):
    +    def __init__(self, *args, **kwargs):
    +        # Cisco NX-OS defaults to fast_cli=True and legacy_mode=False
    +        kwargs.setdefault("fast_cli", True)
    +        kwargs.setdefault("_legacy_mode", False)
    +        return super().__init__(*args, **kwargs)
    +
         def establish_connection(self):
             """Establish SSH connection to the network device"""
             super().establish_connection(width=511, height=511)
     
         def session_preparation(self):
             """Prepare the session after the connection has been established."""
    -        self._test_channel_read()
    -        self.set_base_prompt()
    -        self.set_terminal_width(command="terminal width 511", pattern="terminal")
    +        # IOS-XR has an issue where it echoes the command even though it hasn't returned the prompt
    +        self._test_channel_read(pattern=r"[>#]")
    +        cmd = "terminal width 511"
    +        self.set_terminal_width(command=cmd, pattern=cmd)
             self.disable_paging()
    -        # Clear the read buffer
    -        time.sleep(0.3 * self.global_delay_factor)
    -        self.clear_buffer()
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_base_prompt()
     
         def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
             """IOS-XR requires you not exit from configuration mode."""
    @@ -145,17 +150,21 @@ 

    Module netmiko.cisco.cisco_xr

    output = output.replace("(admin)", "") return check_string in output - def exit_config_mode(self, exit_config="end"): + def exit_config_mode(self, exit_config="end", pattern=""): """Exit configuration mode.""" output = "" if self.check_config_mode(): - output = self.send_command_timing( - exit_config, strip_prompt=False, strip_command=False - ) - if "Uncommitted changes found" in output: - output += self.send_command_timing( - "no", strip_prompt=False, strip_command=False + self.write_channel(self.normalize_cmd(exit_config)) + # Make sure you read until you detect the command echo (avoid getting out of sync) + if self.global_cmd_verify is not False: + output += self.read_until_pattern( + pattern=re.escape(exit_config.strip()) ) + if "Uncommitted changes found" in output: + self.write_channel(self.normalize_cmd("no\n")) + output += self.read_until_pattern(pattern=r"[>#]") + if not re.search(pattern, output, flags=re.M): + output += self.read_until_pattern(pattern=pattern) if self.check_config_mode(): raise ValueError("Failed to exit configuration mode") return output @@ -229,7 +238,7 @@

    Classes

    class CiscoXrBase -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Base Class for cisco-like behavior.

    @@ -366,19 +375,25 @@

    Classes

    Source code
    class CiscoXrBase(CiscoBaseConnection):
    +    def __init__(self, *args, **kwargs):
    +        # Cisco NX-OS defaults to fast_cli=True and legacy_mode=False
    +        kwargs.setdefault("fast_cli", True)
    +        kwargs.setdefault("_legacy_mode", False)
    +        return super().__init__(*args, **kwargs)
    +
         def establish_connection(self):
             """Establish SSH connection to the network device"""
             super().establish_connection(width=511, height=511)
     
         def session_preparation(self):
             """Prepare the session after the connection has been established."""
    -        self._test_channel_read()
    -        self.set_base_prompt()
    -        self.set_terminal_width(command="terminal width 511", pattern="terminal")
    +        # IOS-XR has an issue where it echoes the command even though it hasn't returned the prompt
    +        self._test_channel_read(pattern=r"[>#]")
    +        cmd = "terminal width 511"
    +        self.set_terminal_width(command=cmd, pattern=cmd)
             self.disable_paging()
    -        # Clear the read buffer
    -        time.sleep(0.3 * self.global_delay_factor)
    -        self.clear_buffer()
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_base_prompt()
     
         def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
             """IOS-XR requires you not exit from configuration mode."""
    @@ -483,17 +498,21 @@ 

    Classes

    output = output.replace("(admin)", "") return check_string in output - def exit_config_mode(self, exit_config="end"): + def exit_config_mode(self, exit_config="end", pattern=""): """Exit configuration mode.""" output = "" if self.check_config_mode(): - output = self.send_command_timing( - exit_config, strip_prompt=False, strip_command=False - ) - if "Uncommitted changes found" in output: - output += self.send_command_timing( - "no", strip_prompt=False, strip_command=False + self.write_channel(self.normalize_cmd(exit_config)) + # Make sure you read until you detect the command echo (avoid getting out of sync) + if self.global_cmd_verify is not False: + output += self.read_until_pattern( + pattern=re.escape(exit_config.strip()) ) + if "Uncommitted changes found" in output: + self.write_channel(self.normalize_cmd("no\n")) + output += self.read_until_pattern(pattern=r"[>#]") + if not re.search(pattern, output, flags=re.M): + output += self.read_until_pattern(pattern=pattern) if self.check_config_mode(): raise ValueError("Failed to exit configuration mode") return output @@ -666,23 +685,27 @@

    Methods

    -def exit_config_mode(self, exit_config='end') +def exit_config_mode(self, exit_config='end', pattern='')

    Exit configuration mode.

    Source code -
    def exit_config_mode(self, exit_config="end"):
    +
    def exit_config_mode(self, exit_config="end", pattern=""):
         """Exit configuration mode."""
         output = ""
         if self.check_config_mode():
    -        output = self.send_command_timing(
    -            exit_config, strip_prompt=False, strip_command=False
    -        )
    -        if "Uncommitted changes found" in output:
    -            output += self.send_command_timing(
    -                "no", strip_prompt=False, strip_command=False
    +        self.write_channel(self.normalize_cmd(exit_config))
    +        # Make sure you read until you detect the command echo (avoid getting out of sync)
    +        if self.global_cmd_verify is not False:
    +            output += self.read_until_pattern(
    +                pattern=re.escape(exit_config.strip())
                 )
    +        if "Uncommitted changes found" in output:
    +            self.write_channel(self.normalize_cmd("no\n"))
    +            output += self.read_until_pattern(pattern=r"[>#]")
    +        if not re.search(pattern, output, flags=re.M):
    +            output += self.read_until_pattern(pattern=pattern)
             if self.check_config_mode():
                 raise ValueError("Failed to exit configuration mode")
         return output
    @@ -723,13 +746,13 @@

    Methods

    Source code
    def session_preparation(self):
         """Prepare the session after the connection has been established."""
    -    self._test_channel_read()
    -    self.set_base_prompt()
    -    self.set_terminal_width(command="terminal width 511", pattern="terminal")
    +    # IOS-XR has an issue where it echoes the command even though it hasn't returned the prompt
    +    self._test_channel_read(pattern=r"[>#]")
    +    cmd = "terminal width 511"
    +    self.set_terminal_width(command=cmd, pattern=cmd)
         self.disable_paging()
    -    # Clear the read buffer
    -    time.sleep(0.3 * self.global_delay_factor)
    -    self.clear_buffer()
    + self._test_channel_read(pattern=r"[>#]") + self.set_base_prompt()
    @@ -907,7 +930,7 @@

    Inherited members

    class CiscoXrSSH -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Cisco XR SSH driver.

    @@ -1104,7 +1127,7 @@

    Inherited members

    class CiscoXrTelnet -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Cisco XR Telnet driver.

    diff --git a/docs/netmiko/cisco/index.html b/docs/netmiko/cisco/index.html index 8f748537d..b15d31ee8 100644 --- a/docs/netmiko/cisco/index.html +++ b/docs/netmiko/cisco/index.html @@ -31,6 +31,7 @@

    Module netmiko.cisco

    from netmiko.cisco.cisco_ios import CiscoIosFileTransfer from netmiko.cisco.cisco_ios import InLineTransfer from netmiko.cisco.cisco_asa_ssh import CiscoAsaSSH, CiscoAsaFileTransfer +from netmiko.cisco.cisco_ftd_ssh import CiscoFtdSSH from netmiko.cisco.cisco_nxos_ssh import CiscoNxosSSH, CiscoNxosFileTransfer from netmiko.cisco.cisco_xr import CiscoXrSSH, CiscoXrTelnet, CiscoXrFileTransfer from netmiko.cisco.cisco_wlc_ssh import CiscoWlcSSH @@ -41,6 +42,7 @@

    Module netmiko.cisco

    "CiscoIosSSH", "CiscoIosTelnet", "CiscoAsaSSH", + "CiscoFtdSSH", "CiscoNxosSSH", "CiscoXrSSH", "CiscoXrTelnet", @@ -64,6 +66,10 @@

    Sub-modules

    Subclass specific to Cisco ASA.

    +
    netmiko.cisco.cisco_ftd_ssh
    +
    +

    Subclass specific to Cisco FTD.

    +
    netmiko.cisco.cisco_ios
    @@ -635,6 +641,281 @@

    Inherited members

    +
    +class CiscoFtdSSH +(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +
    +
    +

    Subclass specific to Cisco FTD.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class CiscoFtdSSH(CiscoSSHConnection):
    +    """Subclass specific to Cisco FTD."""
    +
    +    def session_preparation(self):
    +        """Prepare the session after the connection has been established."""
    +        self._test_channel_read()
    +        self.set_base_prompt()
    +
    +    def send_config_set(self, *args, **kwargs):
    +        """Canot change config on FTD via ssh"""
    +        raise NotImplementedError
    +
    +    def enable(self, *args, **kwargs):
    +        """No enable mode on firepower ssh"""
    +        return ""
    +
    +    def config_mode(self, *args, **kwargs):
    +        """No config mode on firepower ssh"""
    +        return ""
    +
    +    def check_config_mode(self, *args, **kwargs):
    +        """No config mode on firepower ssh"""
    +        return False
    +
    +

    Ancestors

    + +

    Methods

    +
    +
    +def check_config_mode(self, *args, **kwargs) +
    +
    +

    No config mode on firepower ssh

    +
    +Source code +
    def check_config_mode(self, *args, **kwargs):
    +    """No config mode on firepower ssh"""
    +    return False
    +
    +
    +
    +def config_mode(self, *args, **kwargs) +
    +
    +

    No config mode on firepower ssh

    +
    +Source code +
    def config_mode(self, *args, **kwargs):
    +    """No config mode on firepower ssh"""
    +    return ""
    +
    +
    +
    +def enable(self, *args, **kwargs) +
    +
    +

    No enable mode on firepower ssh

    +
    +Source code +
    def enable(self, *args, **kwargs):
    +    """No enable mode on firepower ssh"""
    +    return ""
    +
    +
    +
    +def send_config_set(self, *args, **kwargs) +
    +
    +

    Canot change config on FTD via ssh

    +
    +Source code +
    def send_config_set(self, *args, **kwargs):
    +    """Canot change config on FTD via ssh"""
    +    raise NotImplementedError
    +
    +
    +
    +def session_preparation(self) +
    +
    +

    Prepare the session after the connection has been established.

    +
    +Source code +
    def session_preparation(self):
    +    """Prepare the session after the connection has been established."""
    +    self._test_channel_read()
    +    self.set_base_prompt()
    +
    +
    +
    +

    Inherited members

    + +
    class CiscoIosBase (*args, **kwargs) @@ -1685,7 +1966,7 @@

    Inherited members

    class CiscoNxosSSH -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Base Class for cisco-like behavior.

    @@ -1822,16 +2103,22 @@

    Inherited members

    Source code
    class CiscoNxosSSH(CiscoSSHConnection):
    +    def __init__(self, *args, **kwargs):
    +        # Cisco NX-OS defaults to fast_cli=True and legacy_mode=False
    +        kwargs.setdefault("fast_cli", True)
    +        kwargs.setdefault("_legacy_mode", False)
    +        return super().__init__(*args, **kwargs)
    +
         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.set_terminal_width(command="terminal width 511", pattern="terminal")
    +        # NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_terminal_width(
    +            command="terminal width 511", pattern=r"terminal width 511"
    +        )
             self.disable_paging()
    -        # Clear the read buffer
    -        time.sleep(0.3 * self.global_delay_factor)
    -        self.clear_buffer()
    +        self.set_base_prompt()
     
         def normalize_linefeeds(self, a_string):
             """Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
    @@ -1890,14 +2177,14 @@ 

    Methods

    Source code
    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.set_terminal_width(command="terminal width 511", pattern="terminal")
    +    # NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
    +    self._test_channel_read(pattern=r"[>#]")
    +    self.set_terminal_width(
    +        command="terminal width 511", pattern=r"terminal width 511"
    +    )
         self.disable_paging()
    -    # Clear the read buffer
    -    time.sleep(0.3 * self.global_delay_factor)
    -    self.clear_buffer()
    + self.set_base_prompt()
    @@ -3329,7 +3616,7 @@

    Inherited members

    class CiscoXrSSH -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Cisco XR SSH driver.

    @@ -3526,7 +3813,7 @@

    Inherited members

    class CiscoXrTelnet -(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +(*args, **kwargs)

    Cisco XR Telnet driver.

    @@ -3991,6 +4278,7 @@

    Index

  • Sub-modules

    • netmiko.cisco.cisco_asa_ssh
    • +
    • netmiko.cisco.cisco_ftd_ssh
    • netmiko.cisco.cisco_ios
    • netmiko.cisco.cisco_nxos_ssh
    • netmiko.cisco.cisco_s300
    • @@ -4017,6 +4305,16 @@

    • +

      CiscoFtdSSH

      + +
    • +
    • CiscoIosBase

      • save_config
      • diff --git a/docs/netmiko/cisco_base_connection.html b/docs/netmiko/cisco_base_connection.html index 610fb4536..579cd59b8 100644 --- a/docs/netmiko/cisco_base_connection.html +++ b/docs/netmiko/cisco_base_connection.html @@ -54,7 +54,7 @@

        Module netmiko.cisco_base_connection

        """ return super().check_config_mode(check_string=check_string, pattern=pattern) - def config_mode(self, config_command="configure terminal", pattern=""): + def config_mode(self, config_command="configure terminal", pattern="", re_flags=0): """ Enter into configuration mode on remote device. @@ -62,7 +62,9 @@

        Module netmiko.cisco_base_connection

        """ if not pattern: pattern = re.escape(self.base_prompt[:16]) - return super().config_mode(config_command=config_command, pattern=pattern) + return super().config_mode( + config_command=config_command, pattern=pattern, re_flags=re_flags + ) def exit_config_mode(self, exit_config="end", pattern="#"): """Exit from configuration mode.""" @@ -436,7 +438,7 @@

        Classes

        """ return super().check_config_mode(check_string=check_string, pattern=pattern) - def config_mode(self, config_command="configure terminal", pattern=""): + def config_mode(self, config_command="configure terminal", pattern="", re_flags=0): """ Enter into configuration mode on remote device. @@ -444,7 +446,9 @@

        Classes

        """ if not pattern: pattern = re.escape(self.base_prompt[:16]) - return super().config_mode(config_command=config_command, pattern=pattern) + return super().config_mode( + config_command=config_command, pattern=pattern, re_flags=re_flags + ) def exit_config_mode(self, exit_config="end", pattern="#"): """Exit from configuration mode.""" @@ -712,14 +716,14 @@

        Methods

  • -def config_mode(self, config_command='configure terminal', pattern='') +def config_mode(self, config_command='configure terminal', pattern='', re_flags=0)

    Enter into configuration mode on remote device.

    Cisco IOS devices abbreviate the prompt at 20 chars in config mode

    Source code -
    def config_mode(self, config_command="configure terminal", pattern=""):
    +
    def config_mode(self, config_command="configure terminal", pattern="", re_flags=0):
         """
         Enter into configuration mode on remote device.
     
    @@ -727,11 +731,13 @@ 

    Methods

    """ if not pattern: pattern = re.escape(self.base_prompt[:16]) - return super().config_mode(config_command=config_command, pattern=pattern)
    + return super().config_mode( + config_command=config_command, pattern=pattern, re_flags=re_flags + )
    -def enable(self, cmd='enable', pattern='ssword', re_flags=) +def enable(self, cmd='enable', pattern='ssword', re_flags=re.IGNORECASE)

    Enter enable mode.

    @@ -1189,6 +1195,7 @@

    Subclasses

  • BroadcomIcosSSH
  • CalixB6Base
  • CiscoAsaSSH
  • +
  • CiscoFtdSSH
  • CiscoNxosSSH
  • CiscoS300SSH
  • CiscoTpTcCeSSH
  • @@ -1220,6 +1227,7 @@

    Subclasses

  • QuantaMeshSSH
  • RuckusFastironBase
  • SophosSfosSSH
  • +
  • TPLinkJetStreamBase
  • UbiquitiEdgeSSH
  • VyOSSSH
  • diff --git a/docs/netmiko/fortinet/fortinet_ssh.html b/docs/netmiko/fortinet/fortinet_ssh.html index ad4e086c2..98dcd20f4 100644 --- a/docs/netmiko/fortinet/fortinet_ssh.html +++ b/docs/netmiko/fortinet/fortinet_ssh.html @@ -70,7 +70,7 @@

    Module netmiko.fortinet.fortinet_ssh

    self.vdoms = False self._output_mode = "more" - if "Virtual domain configuration: enable" in output: + if re.search(r"Virtual domain configuration: (multiple|enable)", output): self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) @@ -324,7 +324,7 @@

    Classes

    self.vdoms = False self._output_mode = "more" - if "Virtual domain configuration: enable" in output: + if re.search(r"Virtual domain configuration: (multiple|enable)", output): self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) @@ -444,7 +444,7 @@

    Methods

    self.vdoms = False self._output_mode = "more" - if "Virtual domain configuration: enable" in output: + if re.search(r"Virtual domain configuration: (multiple|enable)", output): self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) diff --git a/docs/netmiko/fortinet/index.html b/docs/netmiko/fortinet/index.html index 38004bb03..ce460865a 100644 --- a/docs/netmiko/fortinet/index.html +++ b/docs/netmiko/fortinet/index.html @@ -223,7 +223,7 @@

    Classes

    self.vdoms = False self._output_mode = "more" - if "Virtual domain configuration: enable" in output: + if re.search(r"Virtual domain configuration: (multiple|enable)", output): self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) @@ -343,7 +343,7 @@

    Methods

    self.vdoms = False self._output_mode = "more" - if "Virtual domain configuration: enable" in output: + if re.search(r"Virtual domain configuration: (multiple|enable)", output): self.vdoms = True vdom_additional_command = "config global" output = self.send_command_timing(vdom_additional_command, delay_factor=2) diff --git a/docs/netmiko/hp/hp_procurve.html b/docs/netmiko/hp/hp_procurve.html index e2a9237eb..a968592bd 100644 --- a/docs/netmiko/hp/hp_procurve.html +++ b/docs/netmiko/hp/hp_procurve.html @@ -483,7 +483,7 @@

    Subclasses

    Methods

    -def enable(self, cmd='enable', pattern='password', re_flags=, default_username='manager') +def enable(self, cmd='enable', pattern='password', re_flags=re.IGNORECASE, default_username='manager')

    Enter enable mode

    diff --git a/docs/netmiko/huawei/huawei.html b/docs/netmiko/huawei/huawei.html index 9944c4977..be79bceae 100644 --- a/docs/netmiko/huawei/huawei.html +++ b/docs/netmiko/huawei/huawei.html @@ -52,9 +52,6 @@

    Module netmiko.huawei.huawei

    pattern = rf" {code_cursor_left}" output = re.sub(pattern, "", output) - log.debug("Stripping ANSI escape codes") - log.debug(f"new_output = {output}") - log.debug(f"repr = {repr(output)}") return super().strip_ansi_escape_codes(output) def config_mode(self, config_command="system-view"): @@ -431,9 +428,6 @@

    Classes

    pattern = rf" {code_cursor_left}" output = re.sub(pattern, "", output) - log.debug("Stripping ANSI escape codes") - log.debug(f"new_output = {output}") - log.debug(f"repr = {repr(output)}") return super().strip_ansi_escape_codes(output) def config_mode(self, config_command="system-view"): @@ -697,9 +691,6 @@

    Methods

    pattern = rf" {code_cursor_left}" output = re.sub(pattern, "", output) - log.debug("Stripping ANSI escape codes") - log.debug(f"new_output = {output}") - log.debug(f"repr = {repr(output)}") return super().strip_ansi_escape_codes(output)
    diff --git a/docs/netmiko/index.html b/docs/netmiko/index.html index 21bc65115..3a390eb33 100644 --- a/docs/netmiko/index.html +++ b/docs/netmiko/index.html @@ -47,7 +47,7 @@

    Module netmiko

    # Alternate naming Netmiko = ConnectHandler -__version__ = "3.3.0" +__version__ = "3.3.2" __all__ = ( "ConnectHandler", "ssh_dispatcher", @@ -304,6 +304,10 @@

    Sub-modules

    +
    netmiko.tplink
    +
    +
    +
    netmiko.ubiquiti
    @@ -528,7 +532,8 @@

    Functions

    Source code
    def progress_bar(filename, size, sent, peername=None):
         max_width = 50
    -    filename = filename.decode()
    +    if isinstance(filename, bytes):
    +        filename = filename.decode()
         clear_screen = chr(27) + "[2J"
         terminating_char = "|"
     
    @@ -1672,6 +1677,7 @@ 

    Classes

    print("Interactive SSH session established") return "" + # @m_exec_time def _test_channel_read(self, count=40, pattern=""): """Try to read the channel (generally post login) verify you receive data back. @@ -1703,6 +1709,7 @@

    Classes

    break else: self.write_channel(self.RETURN) + main_delay = _increment_delay(main_delay) time.sleep(main_delay) i += 1 @@ -1737,7 +1744,7 @@

    Classes

    :type delay_factor: int """ if self.fast_cli: - if delay_factor <= self.global_delay_factor: + if delay_factor and delay_factor <= self.global_delay_factor: return delay_factor else: return self.global_delay_factor @@ -1806,6 +1813,10 @@

    Classes

    output = self.read_until_prompt() return output + # Retry by sleeping .33 and then double sleep until 5 attempts (.33, .66, 1.32, etc) + @retry( + wait=wait_exponential(multiplier=0.33, min=0, max=5), stop=stop_after_attempt(5) + ) def set_base_prompt( self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1 ): @@ -1951,13 +1962,19 @@

    Classes

    :param cmd_echo: Deprecated (use cmd_verify instead) :type cmd_echo: bool """ - # For compatibility remove cmd_echo in Netmiko 4.x.x + + # For compatibility; remove cmd_echo in Netmiko 4.x.x if cmd_echo is not None: cmd_verify = cmd_echo output = "" + delay_factor = self.select_delay_factor(delay_factor) - self.clear_buffer() + # Cleanup in future versions of Netmiko + if delay_factor < 1: + if not self._legacy_mode and self.fast_cli: + delay_factor = 1 + if normalize: command_string = self.normalize_cmd(command_string) @@ -1992,7 +2009,7 @@

    Classes

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -2003,6 +2020,11 @@

    Classes

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -2067,6 +2089,8 @@

    Classes

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=True, ): @@ -2192,7 +2216,7 @@

    Classes

    new_data = self.read_channel() else: # nobreak raise IOError( - "Search pattern never detected in send_command_expect: {}".format( + "Search pattern never detected in send_command: {}".format( search_pattern ) ) @@ -2204,7 +2228,7 @@

    Classes

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -2215,6 +2239,11 @@

    Classes

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -2371,7 +2400,7 @@

    Classes

    output = self.read_until_pattern(pattern=pattern) return check_string in output - def config_mode(self, config_command="", pattern=""): + def config_mode(self, config_command="", pattern="", re_flags=0): """Enter into config_mode. :param config_command: Configuration command to send to the device @@ -2379,6 +2408,9 @@

    Classes

    :param pattern: Pattern to terminate reading of channel :type pattern: str + + :param re_flags: Regular expression flags + :type re_flags: RegexFlag """ output = "" if not self.check_config_mode(): @@ -2388,8 +2420,8 @@

    Classes

    output += self.read_until_pattern( pattern=re.escape(config_command.strip()) ) - if not re.search(pattern, output, flags=re.M): - output += self.read_until_pattern(pattern=pattern) + if not re.search(pattern, output, flags=re_flags): + output += self.read_until_pattern(pattern=pattern, re_flags=re_flags) if not self.check_config_mode(): raise ValueError("Failed to enter configuration mode.") return output @@ -2840,17 +2872,19 @@

    Methods

    -def config_mode(self, config_command='', pattern='') +def config_mode(self, config_command='', pattern='', re_flags=0)

    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

    +:type pattern: str

    +

    :param re_flags: Regular expression flags +:type re_flags: RegexFlag

    Source code -
    def config_mode(self, config_command="", pattern=""):
    +
    def config_mode(self, config_command="", pattern="", re_flags=0):
         """Enter into config_mode.
     
         :param config_command: Configuration command to send to the device
    @@ -2858,6 +2892,9 @@ 

    Methods

    :param pattern: Pattern to terminate reading of channel :type pattern: str + + :param re_flags: Regular expression flags + :type re_flags: RegexFlag """ output = "" if not self.check_config_mode(): @@ -2867,8 +2904,8 @@

    Methods

    output += self.read_until_pattern( pattern=re.escape(config_command.strip()) ) - if not re.search(pattern, output, flags=re.M): - output += self.read_until_pattern(pattern=pattern) + if not re.search(pattern, output, flags=re_flags): + output += self.read_until_pattern(pattern=pattern, re_flags=re_flags) if not self.check_config_mode(): raise ValueError("Failed to enter configuration mode.") return output
    @@ -2940,7 +2977,7 @@

    Methods

    -def enable(self, cmd='', pattern='ssword', re_flags=) +def enable(self, cmd='', pattern='ssword', re_flags=re.IGNORECASE)

    Enter enable mode.

    @@ -3425,7 +3462,7 @@

    Methods

    :type delay_factor: int """ if self.fast_cli: - if delay_factor <= self.global_delay_factor: + if delay_factor and delay_factor <= self.global_delay_factor: return delay_factor else: return self.global_delay_factor @@ -3437,7 +3474,7 @@

    Methods

    -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, textfsm_template=None, use_genie=False, cmd_verify=True) +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, textfsm_template=None, use_ttp=False, ttp_template=None, use_genie=False, cmd_verify=True)

    Execute command_string on the SSH channel using a pattern-based mechanism. Generally @@ -3464,6 +3501,11 @@

    Methods

    :type normalize: bool

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None).

    +

    :param use_ttp: Process command output through TTP template (default: False). +:type use_ttp: bool

    +

    :param ttp_template: Name of template to parse output with; can be fully qualified +path, relative path, or name of file in current directory. (default: None). +:type ttp_template: str

    :param use_genie: Process command output through PyATS/Genie parser (default: False). :type normalize: bool

    :param cmd_verify: Verify command echo before proceeding (default: True). @@ -3483,6 +3525,8 @@

    Methods

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=True, ): @@ -3520,6 +3564,13 @@

    Methods

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None). + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type normalize: bool @@ -3601,7 +3652,7 @@

    Methods

    new_data = self.read_channel() else: # nobreak raise IOError( - "Search pattern never detected in send_command_expect: {}".format( + "Search pattern never detected in send_command: {}".format( search_pattern ) ) @@ -3613,7 +3664,7 @@

    Methods

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -3624,6 +3675,11 @@

    Methods

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -3658,7 +3714,7 @@

    Methods

    -def send_command_timing(self, command_string, delay_factor=1, max_loops=150, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, textfsm_template=None, use_genie=False, cmd_verify=False, cmd_echo=None) +def send_command_timing(self, command_string, delay_factor=1, max_loops=150, strip_prompt=True, strip_command=True, normalize=True, use_textfsm=False, textfsm_template=None, use_ttp=False, ttp_template=None, use_genie=False, cmd_verify=False, cmd_echo=None)

    Execute command_string on the SSH channel using a delay-based mechanism. Generally @@ -3681,6 +3737,11 @@

    Methods

    :param textfsm_template: Name of template to parse output with; can be fully qualified path, relative path, or name of file in current directory. (default: None). :type textfsm_template: str

    +

    :param use_ttp: Process command output through TTP template (default: False). +:type use_ttp: bool

    +

    :param ttp_template: Name of template to parse output with; can be fully qualified +path, relative path, or name of file in current directory. (default: None). +:type ttp_template: str

    :param use_genie: Process command output through PyATS/Genie parser (default: False). :type use_genie: bool

    :param cmd_verify: Verify command echo before proceeding (default: False). @@ -3700,6 +3761,8 @@

    Methods

    normalize=True, use_textfsm=False, textfsm_template=None, + use_ttp=False, + ttp_template=None, use_genie=False, cmd_verify=False, cmd_echo=None, @@ -3733,6 +3796,13 @@

    Methods

    path, relative path, or name of file in current directory. (default: None). :type textfsm_template: str + :param use_ttp: Process command output through TTP template (default: False). + :type use_ttp: bool + + :param ttp_template: Name of template to parse output with; can be fully qualified + path, relative path, or name of file in current directory. (default: None). + :type ttp_template: str + :param use_genie: Process command output through PyATS/Genie parser (default: False). :type use_genie: bool @@ -3742,13 +3812,19 @@

    Methods

    :param cmd_echo: Deprecated (use cmd_verify instead) :type cmd_echo: bool """ - # For compatibility remove cmd_echo in Netmiko 4.x.x + + # For compatibility; remove cmd_echo in Netmiko 4.x.x if cmd_echo is not None: cmd_verify = cmd_echo output = "" + delay_factor = self.select_delay_factor(delay_factor) - self.clear_buffer() + # Cleanup in future versions of Netmiko + if delay_factor < 1: + if not self._legacy_mode and self.fast_cli: + delay_factor = 1 + if normalize: command_string = self.normalize_cmd(command_string) @@ -3783,7 +3859,7 @@

    Methods

    strip_prompt=strip_prompt, ) - # If both TextFSM and Genie are set, try TextFSM then Genie + # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie if use_textfsm: structured_output = get_structured_data( output, @@ -3794,6 +3870,11 @@

    Methods

    # If we have structured data; return it. if not isinstance(structured_output, str): return structured_output + if use_ttp: + structured_output = get_structured_data_ttp(output, template=ttp_template) + # If we have structured data; return it. + if not isinstance(structured_output, str): + return structured_output if use_genie: structured_output = get_structured_data_genie( output, platform=self.device_type, command=command_string.strip() @@ -4052,7 +4133,10 @@

    Methods

    :type delay_factor: int

    Source code -
    def set_base_prompt(
    +
    @retry(
    +    wait=wait_exponential(multiplier=0.33, min=0, max=5), stop=stop_after_attempt(5)
    +)
    +def set_base_prompt(
         self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1
     ):
         """Sets self.base_prompt
    @@ -5287,6 +5371,7 @@ 

    Index

  • netmiko.ssh_autodetect
  • netmiko.ssh_exception
  • netmiko.terminal_server
  • +
  • netmiko.tplink
  • netmiko.ubiquiti
  • netmiko.utilities
  • netmiko.vyos
  • diff --git a/docs/netmiko/linux/index.html b/docs/netmiko/linux/index.html index 578792223..e7d1dc966 100644 --- a/docs/netmiko/linux/index.html +++ b/docs/netmiko/linux/index.html @@ -456,7 +456,7 @@

    Methods

    -def enable(self, cmd='sudo -s', pattern='ssword', re_flags=) +def enable(self, cmd='sudo -s', pattern='ssword', re_flags=re.IGNORECASE)

    Attempt to become root.

    diff --git a/docs/netmiko/linux/linux_ssh.html b/docs/netmiko/linux/linux_ssh.html index df2201010..ea20fa72f 100644 --- a/docs/netmiko/linux/linux_ssh.html +++ b/docs/netmiko/linux/linux_ssh.html @@ -622,7 +622,7 @@

    Methods

    -def enable(self, cmd='sudo -s', pattern='ssword', re_flags=) +def enable(self, cmd='sudo -s', pattern='ssword', re_flags=re.IGNORECASE)

    Attempt to become root.

    diff --git a/docs/netmiko/mellanox/index.html b/docs/netmiko/mellanox/index.html index 273433703..1a096d111 100644 --- a/docs/netmiko/mellanox/index.html +++ b/docs/netmiko/mellanox/index.html @@ -246,7 +246,7 @@

    Ancestors

    Methods

    -def enable(self, cmd='enable', pattern='#', re_flags=) +def enable(self, cmd='enable', pattern='#', re_flags=re.IGNORECASE)

    Enter into enable mode.

    diff --git a/docs/netmiko/mellanox/mellanox_mlnxos_ssh.html b/docs/netmiko/mellanox/mellanox_mlnxos_ssh.html index 3706ca0c4..2265ddab4 100644 --- a/docs/netmiko/mellanox/mellanox_mlnxos_ssh.html +++ b/docs/netmiko/mellanox/mellanox_mlnxos_ssh.html @@ -298,7 +298,7 @@

    Ancestors

    Methods

    -def enable(self, cmd='enable', pattern='#', re_flags=) +def enable(self, cmd='enable', pattern='#', re_flags=re.IGNORECASE)

    Enter into enable mode.

    diff --git a/docs/netmiko/mrv/index.html b/docs/netmiko/mrv/index.html index 7240ff880..5b9436858 100644 --- a/docs/netmiko/mrv/index.html +++ b/docs/netmiko/mrv/index.html @@ -494,7 +494,7 @@

    Ancestors

    Methods

    -def enable(self, cmd='enable', pattern='#', re_flags=) +def enable(self, cmd='enable', pattern='#', re_flags=re.IGNORECASE)

    Enable mode on MRV uses no password.

    diff --git a/docs/netmiko/mrv/mrv_ssh.html b/docs/netmiko/mrv/mrv_ssh.html index 884d51b82..229094cd6 100644 --- a/docs/netmiko/mrv/mrv_ssh.html +++ b/docs/netmiko/mrv/mrv_ssh.html @@ -259,7 +259,7 @@

    Ancestors

    Methods

    -def enable(self, cmd='enable', pattern='#', re_flags=) +def enable(self, cmd='enable', pattern='#', re_flags=re.IGNORECASE)

    Enable mode on MRV uses no password.

    diff --git a/docs/netmiko/nokia/index.html b/docs/netmiko/nokia/index.html index c4cc956af..dfffb52e2 100644 --- a/docs/netmiko/nokia/index.html +++ b/docs/netmiko/nokia/index.html @@ -683,7 +683,7 @@

    Methods

    -def enable(self, cmd='enable', pattern='ssword', re_flags=) +def enable(self, cmd='enable', pattern='ssword', re_flags=re.IGNORECASE)

    Enable SR OS administrative mode

    diff --git a/docs/netmiko/nokia/nokia_sros_ssh.html b/docs/netmiko/nokia/nokia_sros_ssh.html index 0f59ad2de..3482f6336 100644 --- a/docs/netmiko/nokia/nokia_sros_ssh.html +++ b/docs/netmiko/nokia/nokia_sros_ssh.html @@ -989,7 +989,7 @@

    Methods

    -def enable(self, cmd='enable', pattern='ssword', re_flags=) +def enable(self, cmd='enable', pattern='ssword', re_flags=re.IGNORECASE)

    Enable SR OS administrative mode

    diff --git a/docs/netmiko/paloalto/paloalto_panos.html b/docs/netmiko/paloalto/paloalto_panos.html index 4954f1d95..8f7df22fe 100644 --- a/docs/netmiko/paloalto/paloalto_panos.html +++ b/docs/netmiko/paloalto/paloalto_panos.html @@ -75,6 +75,7 @@

    Module netmiko.paloalto.paloalto_panos

    def commit( self, + comment=None, force=False, partial=False, device_and_network=False, @@ -111,6 +112,8 @@

    Module netmiko.paloalto.paloalto_panos

    # Select proper command string based on arguments provided command_string = "commit" commit_marker = "configuration committed successfully" + if comment: + command_string += f' description "{comment}"' if force: command_string += " force" if partial: @@ -402,6 +405,7 @@

    Classes

    def commit( self, + comment=None, force=False, partial=False, device_and_network=False, @@ -438,6 +442,8 @@

    Classes

    # Select proper command string based on arguments provided command_string = "commit" commit_marker = "configuration committed successfully" + if comment: + command_string += f' description "{comment}"' if force: command_string += " force" if partial: @@ -578,7 +584,7 @@

    Methods

    -def commit(self, force=False, partial=False, device_and_network=False, policy_and_objects=False, vsys='', no_vsys=False, delay_factor=0.1) +def commit(self, comment=None, force=False, partial=False, device_and_network=False, policy_and_objects=False, vsys='', no_vsys=False, delay_factor=0.1)

    Commit the candidate configuration.

    @@ -594,6 +600,7 @@

    Methods

    Source code
    def commit(
         self,
    +    comment=None,
         force=False,
         partial=False,
         device_and_network=False,
    @@ -630,6 +637,8 @@ 

    Methods

    # Select proper command string based on arguments provided command_string = "commit" commit_marker = "configuration committed successfully" + if comment: + command_string += f' description "{comment}"' if force: command_string += " force" if partial: diff --git a/docs/netmiko/ruckus/ruckus_fastiron.html b/docs/netmiko/ruckus/ruckus_fastiron.html index 9b6a4565a..b868f32c7 100644 --- a/docs/netmiko/ruckus/ruckus_fastiron.html +++ b/docs/netmiko/ruckus/ruckus_fastiron.html @@ -347,7 +347,7 @@

    Subclasses

    Methods

    -def enable(self, cmd='enable', pattern='(ssword|User Name)', re_flags=) +def enable(self, cmd='enable', pattern='(ssword|User Name)', re_flags=re.IGNORECASE)

    Enter enable mode. diff --git a/docs/netmiko/scp_functions.html b/docs/netmiko/scp_functions.html index 1630108d3..4c0256873 100644 --- a/docs/netmiko/scp_functions.html +++ b/docs/netmiko/scp_functions.html @@ -37,7 +37,8 @@

    Module netmiko.scp_functions

    def progress_bar(filename, size, sent, peername=None): max_width = 50 - filename = filename.decode() + if isinstance(filename, bytes): + filename = filename.decode() clear_screen = chr(27) + "[2J" terminating_char = "|" @@ -300,7 +301,8 @@

    Functions

    Source code
    def progress_bar(filename, size, sent, peername=None):
         max_width = 50
    -    filename = filename.decode()
    +    if isinstance(filename, bytes):
    +        filename = filename.decode()
         clear_screen = chr(27) + "[2J"
         terminating_char = "|"
     
    diff --git a/docs/netmiko/tplink/index.html b/docs/netmiko/tplink/index.html
    new file mode 100644
    index 000000000..1fd93ecf1
    --- /dev/null
    +++ b/docs/netmiko/tplink/index.html
    @@ -0,0 +1,549 @@
    +
    +
    +
    +
    +
    +
    +netmiko.tplink API documentation
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Module netmiko.tplink

    +
    +
    +
    +Source code +
    from netmiko.tplink.tplink_jetstream import TPLinkJetStreamSSH, TPLinkJetStreamTelnet
    +
    +__all__ = ["TPLinkJetStreamSSH", "TPLinkJetStreamTelnet"]
    +
    +
    +
    +

    Sub-modules

    +
    +
    netmiko.tplink.tplink_jetstream
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class TPLinkJetStreamSSH +(**kwargs) +
    +
    +

    Base Class for cisco-like behavior.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class TPLinkJetStreamSSH(TPLinkJetStreamBase):
    +    def _override_check_dsa_parameters(parameters):
    +        """
    +        Override check_dsa_parameters from cryptography's dsa.py
    +
    +        Without this the error below occurs:
    +
    +        ValueError: p must be exactly 1024, 2048, or 3072 bits long
    +
    +        Allows for shorter or longer parameters.p to be returned
    +        from the server's host key. This is a HORRIBLE hack and a
    +        security risk, please remove if possible!
    +
    +        By now, with firmware:
    +
    +        2.0.5 Build 20200109 Rel.36203(s)
    +
    +        It's still not possible to remove this hack.
    +        """
    +        if crypto_utils.bit_length(parameters.q) not in [160, 256]:
    +            raise ValueError("q must be exactly 160 or 256 bits long")
    +
    +        if not (1 < parameters.g < parameters.p):
    +            raise ValueError("g, p don't satisfy 1 < g < p.")
    +
    +    dsa._check_dsa_parameters = _override_check_dsa_parameters
    +
    +

    Ancestors

    + +

    Inherited members

    + +
    +
    +class TPLinkJetStreamTelnet +(**kwargs) +
    +
    +

    Base Class for cisco-like behavior.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class TPLinkJetStreamTelnet(TPLinkJetStreamBase):
    +    def telnet_login(
    +        self,
    +        pri_prompt_terminator="#",
    +        alt_prompt_terminator=">",
    +        username_pattern=r"User:",
    +        pwd_pattern=r"Password:",
    +        delay_factor=1,
    +        max_loops=60,
    +    ):
    +        """Telnet login: can be username/password or just password."""
    +        super().telnet_login(
    +            pri_prompt_terminator=pri_prompt_terminator,
    +            alt_prompt_terminator=alt_prompt_terminator,
    +            username_pattern=username_pattern,
    +            pwd_pattern=pwd_pattern,
    +            delay_factor=delay_factor,
    +            max_loops=max_loops,
    +        )
    +
    +

    Ancestors

    + +

    Methods

    +
    +
    +def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>', username_pattern='User:', pwd_pattern='Password:', delay_factor=1, max_loops=60) +
    +
    +

    Telnet login: can be username/password or just password.

    +
    +Source code +
    def telnet_login(
    +    self,
    +    pri_prompt_terminator="#",
    +    alt_prompt_terminator=">",
    +    username_pattern=r"User:",
    +    pwd_pattern=r"Password:",
    +    delay_factor=1,
    +    max_loops=60,
    +):
    +    """Telnet login: can be username/password or just password."""
    +    super().telnet_login(
    +        pri_prompt_terminator=pri_prompt_terminator,
    +        alt_prompt_terminator=alt_prompt_terminator,
    +        username_pattern=username_pattern,
    +        pwd_pattern=pwd_pattern,
    +        delay_factor=delay_factor,
    +        max_loops=max_loops,
    +    )
    +
    +
    +
    +

    Inherited members

    + +
    +
    +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/docs/netmiko/tplink/tplink_jetstream.html b/docs/netmiko/tplink/tplink_jetstream.html new file mode 100644 index 000000000..f345b0fca --- /dev/null +++ b/docs/netmiko/tplink/tplink_jetstream.html @@ -0,0 +1,1186 @@ + + + + + + +netmiko.tplink.tplink_jetstream API documentation + + + + + + + + + +
    +
    +
    +

    Module netmiko.tplink.tplink_jetstream

    +
    +
    +
    +Source code +
    import re
    +import time
    +
    +from cryptography import utils as crypto_utils
    +from cryptography.hazmat.primitives.asymmetric import dsa
    +
    +from netmiko import log
    +from netmiko.cisco_base_connection import CiscoSSHConnection
    +from netmiko.ssh_exception import NetmikoTimeoutException
    +
    +
    +class TPLinkJetStreamBase(CiscoSSHConnection):
    +    def __init__(self, **kwargs):
    +        # TP-Link doesn't have a way to set terminal width which breaks cmd_verify
    +        if kwargs.get("global_cmd_verify") is None:
    +            kwargs["global_cmd_verify"] = False
    +        # TP-Link uses "\r\n" as default_enter for SSH and Telnet
    +        if kwargs.get("default_enter") is None:
    +            kwargs["default_enter"] = "\r\n"
    +        return super().__init__(**kwargs)
    +
    +    def session_preparation(self):
    +        """
    +        Prepare the session after the connection has been established.
    +        """
    +        delay_factor = self.select_delay_factor(delay_factor=0)
    +        time.sleep(0.3 * delay_factor)
    +        self.clear_buffer()
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_base_prompt()
    +        self.enable()
    +        self.disable_paging()
    +        # Clear the read buffer
    +        time.sleep(0.3 * self.global_delay_factor)
    +        self.clear_buffer()
    +
    +    def enable(self, cmd="", pattern="ssword", re_flags=re.IGNORECASE):
    +        """
    +        TPLink JetStream requires you to first execute "enable" and then execute "enable-admin".
    +        This is necessary as "configure" is generally only available at "enable-admin" level
    +
    +        If the user does not have the Admin role, he will need to execute enable-admin to really
    +        enable all functions.
    +        """
    +
    +        # If end-user passes in "cmd" execute that using normal process.
    +        if cmd:
    +            return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
    +
    +        output = ""
    +        msg = (
    +            "Failed to enter enable mode. Please ensure you pass "
    +            "the 'secret' argument to ConnectHandler."
    +        )
    +
    +        cmds = ["enable", "enable-admin"]
    +        if not self.check_enable_mode():
    +            for cmd in cmds:
    +                self.write_channel(self.normalize_cmd(cmd))
    +                try:
    +                    output += self.read_until_prompt_or_pattern(
    +                        pattern=pattern, re_flags=re_flags
    +                    )
    +                    self.write_channel(self.normalize_cmd(self.secret))
    +                    output += self.read_until_prompt()
    +                except NetmikoTimeoutException:
    +                    raise ValueError(msg)
    +                if not self.check_enable_mode():
    +                    raise ValueError(msg)
    +        return output
    +
    +    def config_mode(self, config_command="configure"):
    +        """Enter configuration mode."""
    +        return super().config_mode(config_command=config_command)
    +
    +    def exit_config_mode(self, exit_config="exit", pattern=r"#"):
    +        """
    +        Exit config mode.
    +
    +        Like the Mellanox equipment, the TP-Link Jetstream does not
    +        support a single command to completely exit the configuration mode.
    +
    +        Consequently, need to keep checking and sending "exit".
    +        """
    +        output = ""
    +        check_count = 12
    +        while check_count >= 0:
    +            if self.check_config_mode():
    +                self.write_channel(self.normalize_cmd(exit_config))
    +                output += self.read_until_pattern(pattern=pattern)
    +            else:
    +                break
    +            check_count -= 1
    +
    +        if self.check_config_mode():
    +            raise ValueError("Failed to exit configuration mode")
    +            log.debug(f"exit_config_mode: {output}")
    +
    +        return output
    +
    +    def check_config_mode(self, check_string="(config", pattern=r"#"):
    +        """Check whether device is in configuration mode. Return a boolean."""
    +        return super().check_config_mode(check_string=check_string, pattern=pattern)
    +
    +    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 TP-Link this will be the router prompt with > or #
    +        stripped off.
    +
    +        This will be set on logging in, but not when entering system-view
    +        """
    +        return super().set_base_prompt(
    +            pri_prompt_terminator=pri_prompt_terminator,
    +            alt_prompt_terminator=alt_prompt_terminator,
    +            delay_factor=delay_factor,
    +        )
    +
    +
    +class TPLinkJetStreamSSH(TPLinkJetStreamBase):
    +    def _override_check_dsa_parameters(parameters):
    +        """
    +        Override check_dsa_parameters from cryptography's dsa.py
    +
    +        Without this the error below occurs:
    +
    +        ValueError: p must be exactly 1024, 2048, or 3072 bits long
    +
    +        Allows for shorter or longer parameters.p to be returned
    +        from the server's host key. This is a HORRIBLE hack and a
    +        security risk, please remove if possible!
    +
    +        By now, with firmware:
    +
    +        2.0.5 Build 20200109 Rel.36203(s)
    +
    +        It's still not possible to remove this hack.
    +        """
    +        if crypto_utils.bit_length(parameters.q) not in [160, 256]:
    +            raise ValueError("q must be exactly 160 or 256 bits long")
    +
    +        if not (1 < parameters.g < parameters.p):
    +            raise ValueError("g, p don't satisfy 1 < g < p.")
    +
    +    dsa._check_dsa_parameters = _override_check_dsa_parameters
    +
    +
    +class TPLinkJetStreamTelnet(TPLinkJetStreamBase):
    +    def telnet_login(
    +        self,
    +        pri_prompt_terminator="#",
    +        alt_prompt_terminator=">",
    +        username_pattern=r"User:",
    +        pwd_pattern=r"Password:",
    +        delay_factor=1,
    +        max_loops=60,
    +    ):
    +        """Telnet login: can be username/password or just password."""
    +        super().telnet_login(
    +            pri_prompt_terminator=pri_prompt_terminator,
    +            alt_prompt_terminator=alt_prompt_terminator,
    +            username_pattern=username_pattern,
    +            pwd_pattern=pwd_pattern,
    +            delay_factor=delay_factor,
    +            max_loops=max_loops,
    +        )
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    + +
    +

    Base Class for cisco-like behavior.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class TPLinkJetStreamBase(CiscoSSHConnection):
    +    def __init__(self, **kwargs):
    +        # TP-Link doesn't have a way to set terminal width which breaks cmd_verify
    +        if kwargs.get("global_cmd_verify") is None:
    +            kwargs["global_cmd_verify"] = False
    +        # TP-Link uses "\r\n" as default_enter for SSH and Telnet
    +        if kwargs.get("default_enter") is None:
    +            kwargs["default_enter"] = "\r\n"
    +        return super().__init__(**kwargs)
    +
    +    def session_preparation(self):
    +        """
    +        Prepare the session after the connection has been established.
    +        """
    +        delay_factor = self.select_delay_factor(delay_factor=0)
    +        time.sleep(0.3 * delay_factor)
    +        self.clear_buffer()
    +        self._test_channel_read(pattern=r"[>#]")
    +        self.set_base_prompt()
    +        self.enable()
    +        self.disable_paging()
    +        # Clear the read buffer
    +        time.sleep(0.3 * self.global_delay_factor)
    +        self.clear_buffer()
    +
    +    def enable(self, cmd="", pattern="ssword", re_flags=re.IGNORECASE):
    +        """
    +        TPLink JetStream requires you to first execute "enable" and then execute "enable-admin".
    +        This is necessary as "configure" is generally only available at "enable-admin" level
    +
    +        If the user does not have the Admin role, he will need to execute enable-admin to really
    +        enable all functions.
    +        """
    +
    +        # If end-user passes in "cmd" execute that using normal process.
    +        if cmd:
    +            return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
    +
    +        output = ""
    +        msg = (
    +            "Failed to enter enable mode. Please ensure you pass "
    +            "the 'secret' argument to ConnectHandler."
    +        )
    +
    +        cmds = ["enable", "enable-admin"]
    +        if not self.check_enable_mode():
    +            for cmd in cmds:
    +                self.write_channel(self.normalize_cmd(cmd))
    +                try:
    +                    output += self.read_until_prompt_or_pattern(
    +                        pattern=pattern, re_flags=re_flags
    +                    )
    +                    self.write_channel(self.normalize_cmd(self.secret))
    +                    output += self.read_until_prompt()
    +                except NetmikoTimeoutException:
    +                    raise ValueError(msg)
    +                if not self.check_enable_mode():
    +                    raise ValueError(msg)
    +        return output
    +
    +    def config_mode(self, config_command="configure"):
    +        """Enter configuration mode."""
    +        return super().config_mode(config_command=config_command)
    +
    +    def exit_config_mode(self, exit_config="exit", pattern=r"#"):
    +        """
    +        Exit config mode.
    +
    +        Like the Mellanox equipment, the TP-Link Jetstream does not
    +        support a single command to completely exit the configuration mode.
    +
    +        Consequently, need to keep checking and sending "exit".
    +        """
    +        output = ""
    +        check_count = 12
    +        while check_count >= 0:
    +            if self.check_config_mode():
    +                self.write_channel(self.normalize_cmd(exit_config))
    +                output += self.read_until_pattern(pattern=pattern)
    +            else:
    +                break
    +            check_count -= 1
    +
    +        if self.check_config_mode():
    +            raise ValueError("Failed to exit configuration mode")
    +            log.debug(f"exit_config_mode: {output}")
    +
    +        return output
    +
    +    def check_config_mode(self, check_string="(config", pattern=r"#"):
    +        """Check whether device is in configuration mode. Return a boolean."""
    +        return super().check_config_mode(check_string=check_string, pattern=pattern)
    +
    +    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 TP-Link this will be the router prompt with > or #
    +        stripped off.
    +
    +        This will be set on logging in, but not when entering system-view
    +        """
    +        return super().set_base_prompt(
    +            pri_prompt_terminator=pri_prompt_terminator,
    +            alt_prompt_terminator=alt_prompt_terminator,
    +            delay_factor=delay_factor,
    +        )
    +
    +

    Ancestors

    + +

    Subclasses

    + +

    Methods

    +
    + +
    +

    Check whether device is in configuration mode. Return a boolean.

    +
    +Source code +
    def check_config_mode(self, check_string="(config", pattern=r"#"):
    +    """Check whether device is in configuration mode. Return a boolean."""
    +    return super().check_config_mode(check_string=check_string, pattern=pattern)
    +
    +
    + +
    +

    Enter configuration mode.

    +
    +Source code +
    def config_mode(self, config_command="configure"):
    +    """Enter configuration mode."""
    +    return super().config_mode(config_command=config_command)
    +
    +
    + +
    +

    TPLink JetStream requires you to first execute "enable" and then execute "enable-admin". +This is necessary as "configure" is generally only available at "enable-admin" level

    +

    If the user does not have the Admin role, he will need to execute enable-admin to really +enable all functions.

    +
    +Source code +
    def enable(self, cmd="", pattern="ssword", re_flags=re.IGNORECASE):
    +    """
    +    TPLink JetStream requires you to first execute "enable" and then execute "enable-admin".
    +    This is necessary as "configure" is generally only available at "enable-admin" level
    +
    +    If the user does not have the Admin role, he will need to execute enable-admin to really
    +    enable all functions.
    +    """
    +
    +    # If end-user passes in "cmd" execute that using normal process.
    +    if cmd:
    +        return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
    +
    +    output = ""
    +    msg = (
    +        "Failed to enter enable mode. Please ensure you pass "
    +        "the 'secret' argument to ConnectHandler."
    +    )
    +
    +    cmds = ["enable", "enable-admin"]
    +    if not self.check_enable_mode():
    +        for cmd in cmds:
    +            self.write_channel(self.normalize_cmd(cmd))
    +            try:
    +                output += self.read_until_prompt_or_pattern(
    +                    pattern=pattern, re_flags=re_flags
    +                )
    +                self.write_channel(self.normalize_cmd(self.secret))
    +                output += self.read_until_prompt()
    +            except NetmikoTimeoutException:
    +                raise ValueError(msg)
    +            if not self.check_enable_mode():
    +                raise ValueError(msg)
    +    return output
    +
    +
    + +
    +

    Exit config mode.

    +

    Like the Mellanox equipment, the TP-Link Jetstream does not +support a single command to completely exit the configuration mode.

    +

    Consequently, need to keep checking and sending "exit".

    +
    +Source code +
    def exit_config_mode(self, exit_config="exit", pattern=r"#"):
    +    """
    +    Exit config mode.
    +
    +    Like the Mellanox equipment, the TP-Link Jetstream does not
    +    support a single command to completely exit the configuration mode.
    +
    +    Consequently, need to keep checking and sending "exit".
    +    """
    +    output = ""
    +    check_count = 12
    +    while check_count >= 0:
    +        if self.check_config_mode():
    +            self.write_channel(self.normalize_cmd(exit_config))
    +            output += self.read_until_pattern(pattern=pattern)
    +        else:
    +            break
    +        check_count -= 1
    +
    +    if self.check_config_mode():
    +        raise ValueError("Failed to exit configuration mode")
    +        log.debug(f"exit_config_mode: {output}")
    +
    +    return output
    +
    +
    + +
    +

    Prepare the session after the connection has been established.

    +
    +Source code +
    def session_preparation(self):
    +    """
    +    Prepare the session after the connection has been established.
    +    """
    +    delay_factor = self.select_delay_factor(delay_factor=0)
    +    time.sleep(0.3 * delay_factor)
    +    self.clear_buffer()
    +    self._test_channel_read(pattern=r"[>#]")
    +    self.set_base_prompt()
    +    self.enable()
    +    self.disable_paging()
    +    # Clear the read buffer
    +    time.sleep(0.3 * self.global_delay_factor)
    +    self.clear_buffer()
    +
    +
    + +
    +

    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 TP-Link this will be the router prompt with > or # +stripped off.

    +

    This will be set on logging in, but not when entering system-view

    +
    +Source code +
    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 TP-Link this will be the router prompt with > or #
    +    stripped off.
    +
    +    This will be set on logging in, but not when entering system-view
    +    """
    +    return super().set_base_prompt(
    +        pri_prompt_terminator=pri_prompt_terminator,
    +        alt_prompt_terminator=alt_prompt_terminator,
    +        delay_factor=delay_factor,
    +    )
    +
    +
    +
    +

    Inherited members

    + +
    + +
    +

    Base Class for cisco-like behavior.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class TPLinkJetStreamSSH(TPLinkJetStreamBase):
    +    def _override_check_dsa_parameters(parameters):
    +        """
    +        Override check_dsa_parameters from cryptography's dsa.py
    +
    +        Without this the error below occurs:
    +
    +        ValueError: p must be exactly 1024, 2048, or 3072 bits long
    +
    +        Allows for shorter or longer parameters.p to be returned
    +        from the server's host key. This is a HORRIBLE hack and a
    +        security risk, please remove if possible!
    +
    +        By now, with firmware:
    +
    +        2.0.5 Build 20200109 Rel.36203(s)
    +
    +        It's still not possible to remove this hack.
    +        """
    +        if crypto_utils.bit_length(parameters.q) not in [160, 256]:
    +            raise ValueError("q must be exactly 160 or 256 bits long")
    +
    +        if not (1 < parameters.g < parameters.p):
    +            raise ValueError("g, p don't satisfy 1 < g < p.")
    +
    +    dsa._check_dsa_parameters = _override_check_dsa_parameters
    +
    +

    Ancestors

    + +

    Inherited members

    + +
    + +
    +

    Base Class for cisco-like behavior.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class TPLinkJetStreamTelnet(TPLinkJetStreamBase):
    +    def telnet_login(
    +        self,
    +        pri_prompt_terminator="#",
    +        alt_prompt_terminator=">",
    +        username_pattern=r"User:",
    +        pwd_pattern=r"Password:",
    +        delay_factor=1,
    +        max_loops=60,
    +    ):
    +        """Telnet login: can be username/password or just password."""
    +        super().telnet_login(
    +            pri_prompt_terminator=pri_prompt_terminator,
    +            alt_prompt_terminator=alt_prompt_terminator,
    +            username_pattern=username_pattern,
    +            pwd_pattern=pwd_pattern,
    +            delay_factor=delay_factor,
    +            max_loops=max_loops,
    +        )
    +
    +

    Ancestors

    + +

    Methods

    +
    + +
    +

    Telnet login: can be username/password or just password.

    +
    +Source code +
    def telnet_login(
    +    self,
    +    pri_prompt_terminator="#",
    +    alt_prompt_terminator=">",
    +    username_pattern=r"User:",
    +    pwd_pattern=r"Password:",
    +    delay_factor=1,
    +    max_loops=60,
    +):
    +    """Telnet login: can be username/password or just password."""
    +    super().telnet_login(
    +        pri_prompt_terminator=pri_prompt_terminator,
    +        alt_prompt_terminator=alt_prompt_terminator,
    +        username_pattern=username_pattern,
    +        pwd_pattern=pwd_pattern,
    +        delay_factor=delay_factor,
    +        max_loops=max_loops,
    +    )
    +
    +
    +
    +

    Inherited members

    + +
    +
    +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/docs/netmiko/ubiquiti/edgerouter_ssh.html b/docs/netmiko/ubiquiti/edgerouter_ssh.html new file mode 100644 index 000000000..6fb2f9cd2 --- /dev/null +++ b/docs/netmiko/ubiquiti/edgerouter_ssh.html @@ -0,0 +1,328 @@ + + + + + + +netmiko.ubiquiti.edgerouter_ssh API documentation + + + + + + + + + +
    +
    +
    +

    Module netmiko.ubiquiti.edgerouter_ssh

    +
    +
    +
    +Source code +
    import time
    +from netmiko.vyos.vyos_ssh import VyOSSSH
    +
    +
    +class UbiquitiEdgeRouterSSH(VyOSSSH):
    +    """Implement methods for interacting with EdgeOS EdgeRouter network devices."""
    +
    +    def session_preparation(self):
    +        """Prepare the session after the connection has been established."""
    +        self._test_channel_read()
    +        self.set_base_prompt()
    +        self.set_terminal_width(command="terminal width 512")
    +        self.disable_paging(command="terminal length 0")
    +        # Clear the read buffer
    +        time.sleep(0.3 * self.global_delay_factor)
    +        self.clear_buffer()
    +
    +    def save_config(self, cmd="save", confirm=False, confirm_response=""):
    +        """Saves Config."""
    +        if confirm is True:
    +            raise ValueError("EdgeRouter does not support save_config confirmation.")
    +        output = self.send_command(command_string=cmd)
    +        if "Done" not in output:
    +            raise ValueError(f"Save failed with following errors:\n\n{output}")
    +        return output
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +

    Classes

    +
    +
    +class UbiquitiEdgeRouterSSH +(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +
    +
    +

    Implement methods for interacting with EdgeOS EdgeRouter network devices.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class UbiquitiEdgeRouterSSH(VyOSSSH):
    +    """Implement methods for interacting with EdgeOS EdgeRouter network devices."""
    +
    +    def session_preparation(self):
    +        """Prepare the session after the connection has been established."""
    +        self._test_channel_read()
    +        self.set_base_prompt()
    +        self.set_terminal_width(command="terminal width 512")
    +        self.disable_paging(command="terminal length 0")
    +        # Clear the read buffer
    +        time.sleep(0.3 * self.global_delay_factor)
    +        self.clear_buffer()
    +
    +    def save_config(self, cmd="save", confirm=False, confirm_response=""):
    +        """Saves Config."""
    +        if confirm is True:
    +            raise ValueError("EdgeRouter does not support save_config confirmation.")
    +        output = self.send_command(command_string=cmd)
    +        if "Done" not in output:
    +            raise ValueError(f"Save failed with following errors:\n\n{output}")
    +        return output
    +
    +

    Ancestors

    + +

    Methods

    +
    +
    +def save_config(self, cmd='save', confirm=False, confirm_response='') +
    +
    +

    Saves Config.

    +
    +Source code +
    def save_config(self, cmd="save", confirm=False, confirm_response=""):
    +    """Saves Config."""
    +    if confirm is True:
    +        raise ValueError("EdgeRouter does not support save_config confirmation.")
    +    output = self.send_command(command_string=cmd)
    +    if "Done" not in output:
    +        raise ValueError(f"Save failed with following errors:\n\n{output}")
    +    return output
    +
    +
    +
    +

    Inherited members

    + +
    +
    +
    +
    + +
    + + + + + \ No newline at end of file diff --git a/docs/netmiko/ubiquiti/index.html b/docs/netmiko/ubiquiti/index.html index 57d42e180..9827fde53 100644 --- a/docs/netmiko/ubiquiti/index.html +++ b/docs/netmiko/ubiquiti/index.html @@ -23,9 +23,15 @@

    Module netmiko.ubiquiti

    Source code
    from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH
    +from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH
     from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH
     
    -__all__ = ["UbiquitiEdgeSSH", "UnifiSwitchSSH", "UbiquitiUnifiSwitchSSH"]
    +__all__ = [ + "UbiquitiEdgeRouterSSH", + "UbiquitiEdgeSSH", + "UnifiSwitchSSH", + "UbiquitiUnifiSwitchSSH", +]
    @@ -35,6 +41,10 @@

    Sub-modules

    +
    netmiko.ubiquiti.edgerouter_ssh
    +
    +
    +
    netmiko.ubiquiti.unifiswitch_ssh
    @@ -48,6 +58,240 @@

    Sub-modules

    Classes

    +
    +class UbiquitiEdgeRouterSSH +(ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) +
    +
    +

    Implement methods for interacting with EdgeOS EdgeRouter network devices.

    +
        Initialize attributes for establishing connection to target device.
    +
    +    :param ip: IP address of target device. Not required if `host` is
    +        provided.
    +    :type ip: str
    +
    +    :param host: Hostname of target device. Not required if `ip` is
    +            provided.
    +    :type host: str
    +
    +    :param username: Username to authenticate against target device if
    +            required.
    +    :type username: str
    +
    +    :param password: Password to authenticate against target device if
    +            required.
    +    :type password: str
    +
    +    :param secret: The enable password if target device requires one.
    +    :type secret: str
    +
    +    :param port: The destination port used to connect to the target
    +            device.
    +    :type port: int or None
    +
    +    :param device_type: Class selection based on device type.
    +    :type device_type: str
    +
    +    :param verbose: Enable additional messages to standard output.
    +    :type verbose: bool
    +
    +    :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
    +    :type global_delay_factor: int
    +
    +    :param use_keys: Connect to target device using SSH keys.
    +    :type use_keys: bool
    +
    +    :param key_file: Filename path of the SSH key file to use.
    +    :type key_file: str
    +
    +    :param pkey: SSH key object to use.
    +    :type pkey: paramiko.PKey
    +
    +    :param passphrase: Passphrase to use for encrypted key; password will be used for key
    +            decryption if not specified.
    +    :type passphrase: str
    +
    +    :param allow_agent: Enable use of SSH key-agent.
    +    :type allow_agent: bool
    +
    +    :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
    +            means unknown SSH host keys will be accepted).
    +    :type ssh_strict: bool
    +
    +    :param system_host_keys: Load host keys from the users known_hosts file.
    +    :type system_host_keys: bool
    +    :param alt_host_keys: If `True` host keys will be loaded from the file specified in
    +            alt_key_file.
    +    :type alt_host_keys: bool
    +
    +    :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
    +    :type alt_key_file: str
    +
    +    :param ssh_config_file: File name of OpenSSH configuration file.
    +    :type ssh_config_file: str
    +
    +    :param timeout: Connection timeout.
    +    :type timeout: float
    +
    +    :param session_timeout: Set a timeout for parallel requests.
    +    :type session_timeout: float
    +
    +    :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
    +    :type auth_timeout: float
    +
    +    :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
    +    :type banner_timeout: float
    +
    +    :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
    +            Currently defaults to 0, for backwards compatibility (it will not attempt
    +            to keep the connection alive).
    +    :type keepalive: int
    +
    +    :param default_enter: Character(s) to send to correspond to enter key (default:
    +
    +

    ). +:type default_enter: str

    +
        :param response_return: Character(s) to use in normalized return data to represent
    +            enter key (default:
    +
    +

    ) +:type response_return: str

    +
        :param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
    +            to select smallest of global and specific. Sets default global_delay_factor to .1
    +            (default: False)
    +    :type fast_cli: boolean
    +
    +    :param session_log: File path or BufferedIOBase subclass object to write the session log to.
    +    :type session_log: str
    +
    +    :param session_log_record_writes: The session log generally only records channel reads due
    +            to eliminate command duplication due to command echo. You can enable this if you
    +            want to record both channel reads and channel writes in the log (default: False).
    +    :type session_log_record_writes: boolean
    +
    +    :param session_log_file_mode: "write" or "append" for session_log file mode
    +            (default: "write")
    +    :type session_log_file_mode: str
    +
    +    :param allow_auto_change: Allow automatic configuration changes for terminal settings.
    +            (default: False)
    +    :type allow_auto_change: bool
    +
    +    :param encoding: Encoding to be used when writing bytes to the output channel.
    +            (default: ascii)
    +    :type encoding: str
    +
    +    :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
    +            communication to the target host (default: None).
    +    :type sock: socket
    +
    +    :param global_cmd_verify: Control whether command echo verification is enabled or disabled
    +            (default: None). Global attribute takes precedence over function `cmd_verify`
    +            argument. Value of `None` indicates to use function `cmd_verify` argument.
    +    :type global_cmd_verify: bool|None
    +
    +    :param auto_connect: Control whether Netmiko automatically establishes the connection as
    +            part of the object creation (default: True).
    +    :type auto_connect: bool
    +
    +
    +Source code +
    class UbiquitiEdgeRouterSSH(VyOSSSH):
    +    """Implement methods for interacting with EdgeOS EdgeRouter network devices."""
    +
    +    def session_preparation(self):
    +        """Prepare the session after the connection has been established."""
    +        self._test_channel_read()
    +        self.set_base_prompt()
    +        self.set_terminal_width(command="terminal width 512")
    +        self.disable_paging(command="terminal length 0")
    +        # Clear the read buffer
    +        time.sleep(0.3 * self.global_delay_factor)
    +        self.clear_buffer()
    +
    +    def save_config(self, cmd="save", confirm=False, confirm_response=""):
    +        """Saves Config."""
    +        if confirm is True:
    +            raise ValueError("EdgeRouter does not support save_config confirmation.")
    +        output = self.send_command(command_string=cmd)
    +        if "Done" not in output:
    +            raise ValueError(f"Save failed with following errors:\n\n{output}")
    +        return output
    +
    +

    Ancestors

    + +

    Methods

    +
    +
    +def save_config(self, cmd='save', confirm=False, confirm_response='') +
    +
    +

    Saves Config.

    +
    +Source code +
    def save_config(self, cmd="save", confirm=False, confirm_response=""):
    +    """Saves Config."""
    +    if confirm is True:
    +        raise ValueError("EdgeRouter does not support save_config confirmation.")
    +    output = self.send_command(command_string=cmd)
    +    if "Done" not in output:
    +        raise ValueError(f"Save failed with following errors:\n\n{output}")
    +    return output
    +
    +
    +
    +

    Inherited members

    + +
    class UbiquitiEdgeSSH (ip='', host='', username='', password=None, secret='', port=None, device_type='', verbose=False, global_delay_factor=1, global_cmd_verify=None, use_keys=False, key_file=None, pkey=None, passphrase=None, allow_agent=False, ssh_strict=False, system_host_keys=False, alt_host_keys=False, alt_key_file='', ssh_config_file=None, conn_timeout=5, auth_timeout=None, banner_timeout=15, blocking_timeout=20, timeout=100, session_timeout=60, keepalive=0, default_enter=None, response_return=None, serial_settings=None, fast_cli=False, session_log=None, session_log_record_writes=False, session_log_file_mode='write', allow_auto_change=False, encoding='ascii', sock=None, auto_connect=True) @@ -634,12 +878,19 @@

    Index

  • Sub-modules

  • Classes

    • +

      UbiquitiEdgeRouterSSH

      + +
    • +
    • UbiquitiEdgeSSH

      • check_config_mode
      • diff --git a/docs/netmiko/utilities.html b/docs/netmiko/utilities.html index 15806fbea..f60fb6700 100644 --- a/docs/netmiko/utilities.html +++ b/docs/netmiko/utilities.html @@ -34,6 +34,14 @@

        Module netmiko.utilities

        from netmiko._textfsm import _clitable as clitable from netmiko._textfsm._clitable import CliTableError +try: + from ttp import ttp + + TTP_INSTALLED = True + +except ImportError: + TTP_INSTALLED = False + try: from genie.conf.base import Device from genie.libs.parser.utils import get_parser @@ -43,6 +51,12 @@

        Module netmiko.utilities

        except ImportError: GENIE_INSTALLED = False +# If we are on python < 3.7, we need to force the import of importlib.resources backport +try: + from importlib.resources import path as importresources_path +except ModuleNotFoundError: + from importlib_resources import path as importresources_path + try: import serial.tools.list_ports @@ -50,7 +64,6 @@

        Module netmiko.utilities

        except ImportError: PYSERIAL_INSTALLED = False - # Dictionary mapping 'show run' for vendors with different command SHOW_RUN_MAPPER = { "juniper": "show configuration", @@ -134,8 +147,8 @@

        Module netmiko.utilities

        if files: return files[0] raise IOError( - ".netmiko.yml file not found in NETMIKO_TOOLS environment variable directory, current " - "directory, or home directory." + ".netmiko.yml file not found in NETMIKO_TOOLS environment variable directory," + " current directory, or home directory." ) @@ -249,25 +262,59 @@

        Module netmiko.utilities

        raise ValueError(msg) -def get_template_dir(): - """Find and return the ntc-templates/templates dir.""" - try: - template_dir = os.path.expanduser(os.environ["NET_TEXTFSM"]) +def get_template_dir(_skip_ntc_package=False): + """ + Find and return the directory containing the TextFSM index file. + + Order of preference is: + 1) Find directory in `NET_TEXTFSM` Environment Variable. + 2) Check for pip installed `ntc-templates` location in this environment. + 3) ~/ntc-templates/templates. + + If `index` file is not found in any of these locations, raise ValueError + + :return: directory containing the TextFSM index file + + """ + + msg = """ +Directory containing TextFSM index file not found. + +Please set the NET_TEXTFSM environment variable to point at the directory containing your TextFSM +index file. + +Alternatively, `pip install ntc-templates` (if using ntc-templates). + +""" + + # Try NET_TEXTFSM environment variable + template_dir = os.environ.get("NET_TEXTFSM") + if template_dir is not None: + template_dir = os.path.expanduser(template_dir) index = os.path.join(template_dir, "index") if not os.path.isfile(index): # Assume only base ./ntc-templates specified template_dir = os.path.join(template_dir, "templates") - except KeyError: - # Construct path ~/ntc-templates/templates - home_dir = os.path.expanduser("~") - template_dir = os.path.join(home_dir, "ntc-templates", "templates") + + else: + # Try 'pip installed' ntc-templates + try: + with importresources_path( + package="ntc_templates", resource="templates" + ) as posix_path: + # Example: /opt/venv/netmiko/lib/python3.8/site-packages/ntc_templates/templates + template_dir = str(posix_path) + # This is for Netmiko automated testing + if _skip_ntc_package: + raise ModuleNotFoundError() + + except ModuleNotFoundError: + # Finally check in ~/ntc-templates/templates + home_dir = os.path.expanduser("~") + template_dir = os.path.join(home_dir, "ntc-templates", "templates") index = os.path.join(template_dir, "index") if not os.path.isdir(template_dir) or not os.path.isfile(index): - msg = """ -Valid ntc-templates not found, please install https://github.com/networktocode/ntc-templates -and then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates -directory.""" raise ValueError(msg) return os.path.abspath(template_dir) @@ -330,6 +377,25 @@

        Module netmiko.utilities

        ) +def get_structured_data_ttp(raw_output, template=None): + """ + Convert raw CLI output to structured data using TTP template. + + You can use a straight TextFSM file i.e. specify "template" + """ + if not TTP_INSTALLED: + msg = "\nTTP is not installed. Please PIP install ttp:\n" "pip install ttp\n" + raise ValueError(msg) + + try: + if template: + ttp_parser = ttp(data=raw_output, template=template) + ttp_parser.parse(one=True) + return ttp_parser.result(format="raw") + except Exception: + return raw_output + + def get_structured_data_genie(raw_output, platform, command): if not sys.version_info >= (3, 4): raise ValueError("Genie requires Python >= 3.4") @@ -370,7 +436,7 @@

        Module netmiko.utilities

        device.custom["abstraction"]["order"] = ["os"] device.cli = AttrDict({"execute": None}) try: - # Test of whether their is a parser for the given command (will return Exception if fails) + # Test whether there is a parser for given command (return Exception if fails) get_parser(command, device) parsed_output = device.parse(command, output=raw_output) return parsed_output @@ -573,8 +639,8 @@

        Functions

        if files: return files[0] raise IOError( - ".netmiko.yml file not found in NETMIKO_TOOLS environment variable directory, current " - "directory, or home directory." + ".netmiko.yml file not found in NETMIKO_TOOLS environment variable directory," + " current directory, or home directory." )
  • @@ -686,7 +752,7 @@

    Functions

    device.custom["abstraction"]["order"] = ["os"] device.cli = AttrDict({"execute": None}) try: - # Test of whether their is a parser for the given command (will return Exception if fails) + # Test whether there is a parser for given command (return Exception if fails) get_parser(command, device) parsed_output = device.parse(command, output=raw_output) return parsed_output @@ -694,32 +760,99 @@

    Functions

    return raw_output
    +
    +def get_structured_data_ttp(raw_output, template=None) +
    +
    +

    Convert raw CLI output to structured data using TTP template.

    +

    You can use a straight TextFSM file i.e. specify "template"

    +
    +Source code +
    def get_structured_data_ttp(raw_output, template=None):
    +    """
    +    Convert raw CLI output to structured data using TTP template.
    +
    +    You can use a straight TextFSM file i.e. specify "template"
    +    """
    +    if not TTP_INSTALLED:
    +        msg = "\nTTP is not installed. Please PIP install ttp:\n" "pip install ttp\n"
    +        raise ValueError(msg)
    +
    +    try:
    +        if template:
    +            ttp_parser = ttp(data=raw_output, template=template)
    +            ttp_parser.parse(one=True)
    +            return ttp_parser.result(format="raw")
    +    except Exception:
    +        return raw_output
    +
    +
    def get_template_dir()
    -

    Find and return the ntc-templates/templates dir.

    +

    Find and return the directory containing the TextFSM index file.

    +

    Order of preference is: +1) Find directory in NET_TEXTFSM Environment Variable. +2) Check for pip installed ntc-templates location in this environment. +3) ~/ntc-templates/templates.

    +

    If index file is not found in any of these locations, raise ValueError

    +

    :return: directory containing the TextFSM index file

    Source code -
    def get_template_dir():
    -    """Find and return the ntc-templates/templates dir."""
    -    try:
    -        template_dir = os.path.expanduser(os.environ["NET_TEXTFSM"])
    +
    def get_template_dir(_skip_ntc_package=False):
    +    """
    +    Find and return the directory containing the TextFSM index file.
    +
    +    Order of preference is:
    +    1) Find directory in `NET_TEXTFSM` Environment Variable.
    +    2) Check for pip installed `ntc-templates` location in this environment.
    +    3) ~/ntc-templates/templates.
    +
    +    If `index` file is not found in any of these locations, raise ValueError
    +
    +    :return: directory containing the TextFSM index file
    +
    +    """
    +
    +    msg = """
    +Directory containing TextFSM index file not found.
    +
    +Please set the NET_TEXTFSM environment variable to point at the directory containing your TextFSM
    +index file.
    +
    +Alternatively, `pip install ntc-templates` (if using ntc-templates).
    +
    +"""
    +
    +    # Try NET_TEXTFSM environment variable
    +    template_dir = os.environ.get("NET_TEXTFSM")
    +    if template_dir is not None:
    +        template_dir = os.path.expanduser(template_dir)
             index = os.path.join(template_dir, "index")
             if not os.path.isfile(index):
                 # Assume only base ./ntc-templates specified
                 template_dir = os.path.join(template_dir, "templates")
    -    except KeyError:
    -        # Construct path ~/ntc-templates/templates
    -        home_dir = os.path.expanduser("~")
    -        template_dir = os.path.join(home_dir, "ntc-templates", "templates")
    +
    +    else:
    +        # Try 'pip installed' ntc-templates
    +        try:
    +            with importresources_path(
    +                package="ntc_templates", resource="templates"
    +            ) as posix_path:
    +                # Example: /opt/venv/netmiko/lib/python3.8/site-packages/ntc_templates/templates
    +                template_dir = str(posix_path)
    +                # This is for Netmiko automated testing
    +                if _skip_ntc_package:
    +                    raise ModuleNotFoundError()
    +
    +        except ModuleNotFoundError:
    +            # Finally check in ~/ntc-templates/templates
    +            home_dir = os.path.expanduser("~")
    +            template_dir = os.path.join(home_dir, "ntc-templates", "templates")
     
         index = os.path.join(template_dir, "index")
         if not os.path.isdir(template_dir) or not os.path.isfile(index):
    -        msg = """
    -Valid ntc-templates not found, please install https://github.com/networktocode/ntc-templates
    -and then set the NET_TEXTFSM environment variable to point to the ./ntc-templates/templates
    -directory."""
             raise ValueError(msg)
         return os.path.abspath(template_dir)
    @@ -890,6 +1023,7 @@

    Index

  • find_netmiko_dir
  • get_structured_data
  • get_structured_data_genie
  • +
  • get_structured_data_ttp
  • get_template_dir
  • load_devices
  • load_yaml_file
  • diff --git a/docs/netmiko/vyos/index.html b/docs/netmiko/vyos/index.html index 83dfe0cbc..815a0eb88 100644 --- a/docs/netmiko/vyos/index.html +++ b/docs/netmiko/vyos/index.html @@ -290,6 +290,10 @@

    Ancestors

  • CiscoBaseConnection
  • BaseConnection
  • +

    Subclasses

    +

    Methods

    diff --git a/docs/netmiko/vyos/vyos_ssh.html b/docs/netmiko/vyos/vyos_ssh.html index 093c9b6a0..1e9f27cc2 100644 --- a/docs/netmiko/vyos/vyos_ssh.html +++ b/docs/netmiko/vyos/vyos_ssh.html @@ -386,6 +386,10 @@

    Ancestors

  • CiscoBaseConnection
  • BaseConnection
  • +

    Subclasses

    +

    Methods