: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class A10SSH(CiscoSSHConnection):
"""A10 support."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""A10 requires to be enable mode to disable paging."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- # Will not do anything without A10 specific command
+ # terminal width ill not do anything without A10 specific command
# self.set_terminal_width()
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, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
def session_preparation(self) -> None:
"""A10 requires to be enable mode to disable paging."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- # Will not do anything without A10 specific command
+ # terminal width ill not do anything without A10 specific command
# self.set_terminal_width()
- self.disable_paging(command="terminal length 0")
-
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class A10SSH(CiscoSSHConnection):
"""A10 support."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""A10 requires to be enable mode to disable paging."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- # Will not do anything without A10 specific command
+ # terminal width ill not do anything without A10 specific command
# self.set_terminal_width()
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, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
def session_preparation(self) -> None:
"""A10 requires to be enable mode to disable paging."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- # Will not do anything without A10 specific command
+ # terminal width ill not do anything without A10 specific command
# self.set_terminal_width()
- self.disable_paging(command="terminal length 0")
-
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class AccedianSSH(CiscoSSHConnection):
- def session_preparation(self):
- self._test_channel_read()
+
class AccedianSSH(NoEnable, NoConfig, CiscoSSHConnection):
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[:#]")
self.set_base_prompt()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_enable_mode(self, *args, **kwargs):
- raise AttributeError("Accedian devices do not support enable mode!")
-
- def enable(self, *args, **kwargs):
- raise AttributeError("Accedian devices do not support enable mode!")
-
- def exit_enable_mode(self, *args, **kwargs):
- raise AttributeError("Accedian devices do not support enable mode!")
-
- def check_config_mode(self):
- """Accedian devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Accedian devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Accedian devices do not have a config mode."""
- return ""
def set_base_prompt(
- self, pri_prompt_terminator=":", alt_prompt_terminator="#", delay_factor=2
- ):
+ self,
+ pri_prompt_terminator: str = ":",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 2.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
return self.base_prompt
- def save_config(self, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class AccedianSSH(CiscoSSHConnection):
- def session_preparation(self):
- self._test_channel_read()
+
class AccedianSSH(NoEnable, NoConfig, CiscoSSHConnection):
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[:#]")
self.set_base_prompt()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_enable_mode(self, *args, **kwargs):
- raise AttributeError("Accedian devices do not support enable mode!")
-
- def enable(self, *args, **kwargs):
- raise AttributeError("Accedian devices do not support enable mode!")
-
- def exit_enable_mode(self, *args, **kwargs):
- raise AttributeError("Accedian devices do not support enable mode!")
-
- def check_config_mode(self):
- """Accedian devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Accedian devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Accedian devices do not have a config mode."""
- return ""
def set_base_prompt(
- self, pri_prompt_terminator=":", alt_prompt_terminator="#", delay_factor=2
- ):
+ self,
+ pri_prompt_terminator: str = ":",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 2.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
return self.base_prompt
- def save_config(self, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
class AdtranOSTelnet(AdtranOSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
@@ -101,175 +116,163 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class AdtranOSTelnet(AdtranOSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class AdtranOSTelnet(AdtranOSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
Alcatel-Lucent Enterprise AOS support (AOS6 and AOS8).
@@ -91,172 +68,121 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class AlcatelAosSSH(CiscoSSHConnection):
+
class AlcatelAosSSH(NoEnable, NoConfig, CiscoSSHConnection):
"""Alcatel-Lucent Enterprise AOS support (AOS6 and AOS8)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
# Prompt can be anything, but best practice is to end with > or #
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_enable_mode(self, *args, **kwargs):
- """No enable mode on AOS"""
- pass
-
- def enable(self, *args, **kwargs):
- """No enable mode on AOS"""
- pass
-
- def exit_enable_mode(self, *args, **kwargs):
- """No enable mode on AOS"""
- pass
-
- def check_config_mode(self, *args, **kwargs):
- """No config mode on AOS"""
- pass
-
- def config_mode(self, *args, **kwargs):
- """No config mode on AOS"""
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No config mode on AOS"""
- return ""
def save_config(
- self, cmd="write memory flash-synchro", confirm=False, confirm_response=""
- ):
+ self,
+ cmd: str = "write memory flash-synchro",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Save Config"""
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
@@ -264,84 +190,14 @@
Alcatel-Lucent Enterprise AOS support (AOS6 and AOS8).
@@ -53,172 +53,121 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class AlcatelAosSSH(CiscoSSHConnection):
+
class AlcatelAosSSH(NoEnable, NoConfig, CiscoSSHConnection):
"""Alcatel-Lucent Enterprise AOS support (AOS6 and AOS8)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
# Prompt can be anything, but best practice is to end with > or #
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_enable_mode(self, *args, **kwargs):
- """No enable mode on AOS"""
- pass
-
- def enable(self, *args, **kwargs):
- """No enable mode on AOS"""
- pass
-
- def exit_enable_mode(self, *args, **kwargs):
- """No enable mode on AOS"""
- pass
-
- def check_config_mode(self, *args, **kwargs):
- """No config mode on AOS"""
- pass
-
- def config_mode(self, *args, **kwargs):
- """No config mode on AOS"""
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No config mode on AOS"""
- return ""
def save_config(
- self, cmd="write memory flash-synchro", confirm=False, confirm_response=""
- ):
+ self,
+ cmd: str = "write memory flash-synchro",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Save Config"""
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
@@ -226,84 +175,14 @@
Implement methods for interacting with Allied Telesis devices.
@@ -89,138 +89,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class AlliedTelesisAwplusBase(CiscoBaseConnection):
"""Implement methods for interacting with Allied Telesis devices."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
@@ -233,23 +206,23 @@
Implement methods for interacting with Allied Telesis devices.
@@ -371,131 +344,104 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implement methods for interacting with Allied Telesis devices.
@@ -53,131 +53,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ApresiaAeosBase(CiscoSSHConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def disable_paging(self, command="", delay_factor=1):
- self.enable()
- check_command = "show running-config | include terminal length 0"
- output = self.send_command(check_command)
+ def disable_paging(
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
- if self.allow_auto_change and "terminal length 0" not in output:
- self.send_config_set("terminal length 0")
- self.exit_enable_mode()
+ self.enable()
+ check_command = f"show running-config | include {command}"
+ show_run = self._send_command_str(check_command)
+
+ output = ""
+ if self.allow_auto_change and command not in show_run:
+ output += super().disable_paging(
+ command=command,
+ delay_factor=delay_factor,
+ cmd_verify=cmd_verify,
+ pattern=pattern,
+ )
+ self.exit_enable_mode()
+ return output
Ancestors
@@ -243,14 +238,11 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ApresiaAeosTelnet(ApresiaAeosBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ApresiaAeosTelnet(ApresiaAeosBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
cmd = "terminal width 511"
# Arista will echo immediately and then when the device really responds (like NX-OS)
@@ -319,16 +298,18 @@
def config_mode(
+ self,
+ config_command: str = "configure terminal",
+ pattern: str = "",
+ re_flags: int = 0,
+) -> str:
"""Force arista to read pattern all the way to prompt on the next line."""
if not re_flags:
@@ -433,7 +428,7 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
cmd = "terminal width 511"
# Arista will echo immediately and then when the device really responds (like NX-OS)
@@ -450,7 +445,6 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class AristaTelnet(AristaBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class AristaTelnet(AristaBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
For use with Aruba OS Controllers.
"""
-import time
-import re
+from typing import Any
from netmiko.cisco_base_connection import CiscoSSHConnection
class ArubaSSH(CiscoSSHConnection):
"""Aruba OS support"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r"
# Aruba has an auto-complete on space behavior that is problematic
@@ -46,36 +45,35 @@
Module netmiko.aruba.aruba_ssh
kwargs["global_cmd_verify"] = False
return super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Aruba OS requires enable mode to disable paging."""
# Aruba switches output ansi codes
self.ansi_escape_codes = True
-
- delay_factor = self.select_delay_factor(delay_factor=0)
- time.sleep(1 * delay_factor)
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- self.disable_paging(command="no paging")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="no page")
- def check_config_mode(self, check_string="(config) #", pattern=""):
+ def check_config_mode(
+ self, check_string: str = "(config) #", pattern: str = r"[>#]"
+ ) -> bool:
"""
Checks if the device is in configuration mode or not.
Aruba uses "(<controller name>) (config) #" as config prompt
"""
- if not pattern:
- pattern = re.escape(self.base_prompt[:16])
return super().check_config_mode(check_string=check_string, pattern=pattern)
- def config_mode(self, config_command="configure term", pattern=""):
- """
- Aruba auto completes on space so 'configure' needs fully spelled-out.
- """
- return super().config_mode(config_command=config_command, pattern=pattern)
+ def config_mode(
+ self,
+ config_command: str = "configure term",
+ pattern: str = "",
+ re_flags: int = 0,
+ ) -> str:
+ """Aruba auto completes on space so 'configure' needs fully spelled-out."""
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
@@ -97,138 +95,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ArubaSSH(CiscoSSHConnection):
"""Aruba OS support"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r"
# Aruba has an auto-complete on space behavior that is problematic
@@ -236,36 +207,35 @@
Classes
kwargs["global_cmd_verify"] = False
return super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Aruba OS requires enable mode to disable paging."""
# Aruba switches output ansi codes
self.ansi_escape_codes = True
-
- delay_factor = self.select_delay_factor(delay_factor=0)
- time.sleep(1 * delay_factor)
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- self.disable_paging(command="no paging")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="no page")
- def check_config_mode(self, check_string="(config) #", pattern=""):
+ def check_config_mode(
+ self, check_string: str = "(config) #", pattern: str = r"[>#]"
+ ) -> bool:
"""
Checks if the device is in configuration mode or not.
Aruba uses "(<controller name>) (config) #" as config prompt
"""
- if not pattern:
- pattern = re.escape(self.base_prompt[:16])
return super().check_config_mode(check_string=check_string, pattern=pattern)
- def config_mode(self, config_command="configure term", pattern=""):
- """
- Aruba auto completes on space so 'configure' needs fully spelled-out.
- """
- return super().config_mode(config_command=config_command, pattern=pattern)
+ def config_mode(
+ self,
+ config_command: str = "configure term",
+ pattern: str = "",
+ re_flags: int = 0,
+ ) -> str:
+ """Aruba auto completes on space so 'configure' needs fully spelled-out."""
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ArubaSSH(CiscoSSHConnection):
"""Aruba OS support"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r"
# Aruba has an auto-complete on space behavior that is problematic
@@ -192,36 +165,35 @@
Classes
kwargs["global_cmd_verify"] = False
return super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Aruba OS requires enable mode to disable paging."""
# Aruba switches output ansi codes
self.ansi_escape_codes = True
-
- delay_factor = self.select_delay_factor(delay_factor=0)
- time.sleep(1 * delay_factor)
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
- self.disable_paging(command="no paging")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="no page")
- def check_config_mode(self, check_string="(config) #", pattern=""):
+ def check_config_mode(
+ self, check_string: str = "(config) #", pattern: str = r"[>#]"
+ ) -> bool:
"""
Checks if the device is in configuration mode or not.
Aruba uses "(<controller name>) (config) #" as config prompt
"""
- if not pattern:
- pattern = re.escape(self.base_prompt[:16])
return super().check_config_mode(check_string=check_string, pattern=pattern)
- def config_mode(self, config_command="configure term", pattern=""):
- """
- Aruba auto completes on space so 'configure' needs fully spelled-out.
- """
- return super().config_mode(config_command=config_command, pattern=pattern)
+ def config_mode(
+ self,
+ config_command: str = "configure term",
+ pattern: str = "",
+ re_flags: int = 0,
+ ) -> str:
+ """Aruba auto completes on space so 'configure' needs fully spelled-out."""
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
else:
self.protocol = "ssh"
+ self.key_policy: paramiko.client.MissingHostKeyPolicy
if not ssh_strict:
self.key_policy = paramiko.AutoAddPolicy()
else:
@@ -369,6 +452,7 @@
Module netmiko.base_connection
self.system_host_keys = system_host_keys
self.alt_host_keys = alt_host_keys
self.alt_key_file = alt_key_file
+ self.disabled_algorithms = disabled_algorithms or {}
# For SSH proxy support
self.ssh_config_file = ssh_config_file
@@ -377,25 +461,30 @@
Module netmiko.base_connection
if auto_connect:
self._open()
- def _open(self):
+ def _open(self) -> None:
"""Decouple connection creation from __init__ for mocking."""
self._modify_connection_params()
self.establish_connection()
self._try_session_preparation()
- def __enter__(self):
+ def __enter__(self) -> "BaseConnection":
"""Establish a session using a Context Manager."""
return self
- def __exit__(self, exc_type, exc_value, traceback):
+ def __exit__(
+ self,
+ exc_type: Optional[Type[BaseException]],
+ exc_value: Optional[BaseException],
+ traceback: Optional[TracebackType],
+ ) -> None:
"""Gracefully close connection on Context Manager exit."""
self.disconnect()
- def _modify_connection_params(self):
+ def _modify_connection_params(self) -> None:
"""Modify connection parameters prior to SSH connection."""
pass
- def _timeout_exceeded(self, start, msg="Timeout exceeded!"):
+ def _timeout_exceeded(self, start: float, msg: str = "Timeout exceeded!") -> bool:
"""Raise NetmikoTimeoutException if waiting too much in the serving queue.
:param start: Initial start time to see if session lock timeout has been exceeded
@@ -412,7 +501,7 @@
Module netmiko.base_connection
raise NetmikoTimeoutException(msg)
return False
- def _lock_netmiko_session(self, start=None):
+ def _lock_netmiko_session(self, start: Optional[float] = None) -> bool:
"""Try to acquire the Netmiko session lock. If not available, wait in the queue until
the channel is available again.
@@ -428,68 +517,33 @@
Module netmiko.base_connection
time.sleep(0.1)
return True
- def _unlock_netmiko_session(self):
+ def _unlock_netmiko_session(self) -> None:
"""
Release the channel at the end of the task.
"""
if self._session_locker.locked():
self._session_locker.release()
- def _write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+ def _autodetect_fs(self, cmd: str = "", pattern: str = "") -> str:
+ raise NotImplementedError
- :param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
- """
- if self.protocol == "ssh":
- self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))
- elif self.protocol == "telnet":
- self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
- elif self.protocol == "serial":
- self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
- self.remote_conn.flush()
- else:
- raise ValueError("Invalid protocol specified")
- try:
- log.debug(
- "write_channel: {}".format(
- write_bytes(out_data, encoding=self.encoding)
- )
- )
- if self._session_log_fin or self.session_log_record_writes:
- self._write_session_log(out_data)
- except UnicodeDecodeError:
- # Don't log non-ASCII characters; this is null characters and telnet IAC (PY2)
- pass
+ def _enter_shell(self) -> str:
+ raise NotImplementedError
- def _write_session_log(self, data):
- if self.session_log is not None and len(data) > 0:
- # Hide the password and secret in the session_log
- if self.password:
- data = data.replace(self.password, "********")
- if self.secret:
- data = data.replace(self.secret, "********")
- if isinstance(self.session_log, io.BufferedIOBase):
- data = self.normalize_linefeeds(data)
- self.session_log.write(write_bytes(data, encoding=self.encoding))
- else:
- self.session_log.write(self.normalize_linefeeds(data))
- self.session_log.flush()
+ def _return_cli(self) -> str:
+ raise NotImplementedError
- def write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+ @lock_channel
+ @log_writes
+ def write_channel(self, out_data: str) -> None:
+ """Generic method that will write data out the channel.
:param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
+ :type out_data: str
"""
- self._lock_netmiko_session()
- try:
- self._write_channel(out_data)
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+ self.channel.write_channel(out_data)
- def is_alive(self):
+ def is_alive(self) -> bool:
"""Returns a boolean flag with the state of the connection."""
null = chr(0)
if self.remote_conn is None:
@@ -501,9 +555,11 @@
Module netmiko.base_connection
# IAC = Interpret as Command; it comes before the NOP.
log.debug("Sending IAC + NOP")
# Need to send multiple times to test connection
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
+ telnet_socket = self.remote_conn.get_socket()
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
return True
except AttributeError:
return False
@@ -513,203 +569,236 @@
Module netmiko.base_connection
# Try sending ASCII null byte to maintain the connection alive
log.debug("Sending the NULL byte")
self.write_channel(null)
- return self.remote_conn.transport.is_active()
+ assert isinstance(self.remote_conn, paramiko.Channel)
+ assert self.remote_conn.transport is not None
+ result = self.remote_conn.transport.is_active()
+ assert isinstance(result, bool)
+ return result
except (socket.error, EOFError):
log.error("Unable to send", exc_info=True)
# If unable to send, we can tell for sure that the connection is unusable
return False
return False
- def _read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- if self.protocol == "ssh":
- output = ""
- while True:
- if self.remote_conn.recv_ready():
- outbuf = self.remote_conn.recv(MAX_BUFFER)
- if len(outbuf) == 0:
- raise EOFError("Channel stream closed by remote device.")
- output += outbuf.decode("utf-8", "ignore")
- else:
- break
- elif self.protocol == "telnet":
- output = self.remote_conn.read_very_eager().decode("utf-8", "ignore")
- elif self.protocol == "serial":
- output = ""
- while self.remote_conn.in_waiting > 0:
- output += self.remote_conn.read(self.remote_conn.in_waiting).decode(
- "utf-8", "ignore"
- )
+ @lock_channel
+ def read_channel(self) -> str:
+ """Generic handler that will read all the data from given channel."""
+ new_data = self.channel.read_channel()
+ new_data = self.normalize_linefeeds(new_data)
if self.ansi_escape_codes:
- output = self.strip_ansi_escape_codes(output)
- log.debug(f"read_channel: {output}")
- self._write_session_log(output)
+ new_data = self.strip_ansi_escape_codes(new_data)
+ log.debug(f"read_channel: {new_data}")
+ if self.session_log:
+ self.session_log.write(new_data)
+
+ # If data had been previously saved to the buffer, the prepend it to output
+ # do post read_channel so session_log/log doesn't record buffered data twice
+ if self._read_buffer:
+ output = self._read_buffer + new_data
+ self._read_buffer = ""
+ else:
+ output = new_data
return output
- def read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- output = ""
- self._lock_netmiko_session()
- try:
- output = self._read_channel()
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
- return output
+ def read_until_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel until pattern is detected.
- def _read_channel_expect(self, pattern="", re_flags=0, max_loops=150):
- """Function that reads channel until pattern is detected.
+ Will return string up to and including pattern.
- pattern takes a regular expression.
+ Returns ReadTimeout if pattern not detected in read_timeout seconds.
- By default pattern will be self.base_prompt
+ :param pattern: Regular expression pattern used to identify that reading is done.
- Note: this currently reads beyond pattern. In the case of SSH it reads MAX_BUFFER.
- In the case of telnet it reads all non-blocking data.
+ :param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+ A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+ reading indefinitely until pattern is detected.
- There are dependencies here like determining whether in config_mode that are actually
- depending on reading beyond pattern.
+ :param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
- :param pattern: Regular expression pattern used to identify the command is done \
- (defaults to self.base_prompt)
- :type pattern: str (regular expression)
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of max_loops with read_until_pattern.
+You should convert all uses of max_loops over to read_timeout=x
+where x is the total number of seconds to wait before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
- :param max_loops: max number of iterations to read the channel before raising exception.
- Will default to be based upon self.timeout.
- :type max_loops: int
- """
output = ""
- if not pattern:
- pattern = re.escape(self.base_prompt)
- log.debug(f"Pattern is: {pattern}")
-
- i = 1
- loop_delay = 0.1
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # argument for backwards compatibility).
- if max_loops == 150:
- max_loops = int(self.timeout / loop_delay)
- while i < max_loops:
- if self.protocol == "ssh":
- try:
- # If no data available will wait timeout seconds trying to read
- self._lock_netmiko_session()
- new_data = self.remote_conn.recv(MAX_BUFFER)
- if len(new_data) == 0:
- raise EOFError("Channel stream closed by remote device.")
- new_data = new_data.decode("utf-8", "ignore")
- if self.ansi_escape_codes:
- new_data = self.strip_ansi_escape_codes(new_data)
- log.debug(f"_read_channel_expect read_data: {new_data}")
- output += new_data
- self._write_session_log(new_data)
- except socket.timeout:
- raise NetmikoTimeoutException(
- "Timed-out reading channel, data not available."
- )
- finally:
- self._unlock_netmiko_session()
- elif self.protocol == "telnet" or "serial":
- output += self.read_channel()
+ loop_delay = 0.01
+ start_time = time.time()
+ # if read_timeout == 0 or 0.0 keep reading indefinitely
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ output += self.read_channel()
if re.search(pattern, output, flags=re_flags):
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ # The string matched by pattern must be retained in the output string.
+ # re.split will do this if capturing parentesis are used.
+ if len(results) == 2:
+ # no capturing parenthesis, convert and try again.
+ pattern = f"({pattern})"
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ if len(results) != 3:
+ # well, we tried
+ msg = f"""Unable to successfully split output based on pattern:
+pattern={pattern}
+output={repr(output)}
+results={results}
+"""
+ raise ReadException(msg)
+
+ # Process such that everything before and including pattern is return.
+ # Everything else is retained in the _read_buffer
+ output, match_str, buffer = results
+ output = output + match_str
+ if buffer:
+ self._read_buffer += buffer
log.debug(f"Pattern found: {pattern} {output}")
return output
- time.sleep(loop_delay * self.global_delay_factor)
- i += 1
- raise NetmikoTimeoutException(
- f"Timed-out reading channel, pattern not found in output: {pattern}"
- )
+ time.sleep(loop_delay)
+
+ msg = f"""\n\nPattern not detected: {repr(pattern)} in output.
+
+Things you might try to fix this:
+1. Adjust the regex pattern to better identify the terminating string. Note, in
+many situations the pattern is automatically based on the network device's prompt.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.\n\n"""
+ raise ReadTimeout(msg)
- def _read_channel_timing(self, delay_factor=1, max_loops=150):
+ def read_channel_timing(
+ self,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ ) -> str:
"""Read data on the channel based on timing delays.
- Attempt to read channel max_loops number of times. If no data this will cause a 15 second
- delay.
+ General pattern is keep reading until no new data is read.
+ Once no new data is read wait `last_read` amount of time (one last read).
+ As long as no new data, then return data.
+
+ `read_timeout` is an absolute timer for how long to keep reading (which presupposes
+ we are still getting new data).
- Once data is encountered read channel for another two seconds (2 * delay_factor) to make
- sure reading of channel is complete.
+ Setting `read_timeout` to zero will cause read_channel_timing to never expire based
+ on an absolute timeout. It will only complete based on timeout based on their being
+ no new data.
- :param delay_factor: multiplicative factor to adjust delay when reading channel (delays
- get multiplied by this factor)
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: maximum number of loops to iterate through before returning channel data.
- Will default to be based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
- # Time to delay in each read loop
- loop_delay = 0.1
- final_delay = 2
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 150:
- max_loops = int(self.timeout / loop_delay)
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
- # FIX: Cleanup in future versions of Netmiko
- if delay_factor < 1:
- if not self._legacy_mode and self.fast_cli:
- delay_factor = 1
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+ # Time to delay in each read loop
+ loop_delay = 0.1
channel_data = ""
- i = 0
- while i <= max_loops:
- time.sleep(loop_delay * delay_factor)
+ start_time = time.time()
+
+ # Set read_timeout to 0 to never timeout
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ time.sleep(loop_delay)
new_data = self.read_channel()
+ # gather new output
if new_data:
channel_data += new_data
- else:
- # Safeguard to make sure really done
- time.sleep(final_delay * delay_factor)
+ # if we have some output, but nothing new, then do the last read
+ elif channel_data != "":
+ # Make sure really done (i.e. no new data)
+ time.sleep(last_read)
new_data = self.read_channel()
if not new_data:
break
else:
channel_data += new_data
- i += 1
- return channel_data
+ else:
+ msg = f"""\n
+read_channel_timing's absolute timer expired.
- def read_until_prompt(self, *args, **kwargs):
- """Read channel until self.base_prompt detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+The network device was continually outputting data for longer than {read_timeout}
+seconds.
- def read_until_pattern(self, *args, **kwargs):
- """Read channel until pattern detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+If this is expected i.e. the command you are executing is continually emitting
+data for a long period of time, then you can set 'read_timeout=x' seconds. If
+you want Netmiko to keep reading indefinitely (i.e. to only stop when there is
+no new data), then you can set 'read_timeout=0'.
- def read_until_prompt_or_pattern(self, pattern="", re_flags=0):
- """Read until either self.base_prompt or pattern is detected.
+You can look at the Netmiko session_log or debug log for more information.
- :param pattern: the pattern used to identify that the output is complete (i.e. stop \
- reading when pattern is detected). pattern will be combined with self.base_prompt to \
- terminate output reading when the first of self.base_prompt or pattern is detected.
- :type pattern: regular expression string
+"""
+ raise ReadTimeout(msg)
+ return channel_data
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
+ def read_until_prompt(
+ self,
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel up to and including self.base_prompt."""
+ pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ pattern = f"{pattern}.*"
+ return self.read_until_pattern(
+ pattern=pattern,
+ re_flags=re_flags,
+ max_loops=max_loops,
+ read_timeout=read_timeout,
+ )
- """
- combined_pattern = re.escape(self.base_prompt)
+ def read_until_prompt_or_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read until either self.base_prompt or pattern is detected."""
+ prompt_pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ prompt_pattern = f"{prompt_pattern}.*"
if pattern:
- combined_pattern = r"({}|{})".format(combined_pattern, pattern)
- return self._read_channel_expect(combined_pattern, re_flags=re_flags)
+ combined_pattern = r"(?:{}|{})".format(prompt_pattern, pattern)
+ else:
+ combined_pattern = prompt_pattern
+ return self.read_until_pattern(
+ pattern=combined_pattern,
+ re_flags=re_flags,
+ max_loops=max_loops,
+ read_timeout=read_timeout,
+ )
def serial_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:[Uu]ser:|sername|ogin)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
- self.telnet_login(
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:[Uu]ser:|sername|ogin)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
+ return self.telnet_login(
pri_prompt_terminator,
alt_prompt_terminator,
username_pattern,
@@ -720,33 +809,28 @@
Module netmiko.base_connection
def telnet_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
"""Telnet login. Can be username/password or just password.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param username_pattern: Pattern used to identify the username prompt
- :type username_pattern: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
:param max_loops: Controls the wait time in conjunction with the delay_factor
- (default: 20)
"""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
+ # Revert telnet_login back to old speeds/delays
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -772,6 +856,7 @@
Module netmiko.base_connection
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -791,6 +876,7 @@
Module netmiko.base_connection
time.sleep(0.5 * delay_factor)
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -806,10 +892,11 @@
Module netmiko.base_connection
return return_msg
msg = f"Login failed: {self.host}"
+ assert self.remote_conn is not None
self.remote_conn.close()
raise NetmikoAuthenticationException(msg)
- def _try_session_preparation(self):
+ def _try_session_preparation(self) -> None:
"""
In case of an exception happening during `session_preparation()` Netmiko should
gracefully clean-up after itself. This might be challenging for library users
@@ -822,7 +909,7 @@
Module netmiko.base_connection
self.disconnect()
raise
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -830,31 +917,27 @@
Module netmiko.base_connection
early on in the session.
In general, it should include:
- self._test_channel_read()
+ self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
- self.disable_paging()
self.set_terminal_width()
- self.clear_buffer()
+ self.disable_paging()
"""
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def _use_ssh_config(self, dict_arg):
+ def _use_ssh_config(self, dict_arg: Dict[str, Any]) -> Dict[str, Any]:
"""Update SSH connection parameters based on contents of SSH config file.
:param dict_arg: Dictionary of SSH connection parameters
- :type dict_arg: dict
"""
connect_dict = dict_arg.copy()
# Use SSHConfig to generate source content.
+ assert self.ssh_config_file is not None
full_path = path.abspath(path.expanduser(self.ssh_config_file))
+ source: Union[paramiko.config.SSHConfigDict, Dict[str, Any]]
if path.exists(full_path):
ssh_config_instance = paramiko.SSHConfig()
with io.open(full_path, "rt", encoding="utf-8") as f:
@@ -864,6 +947,7 @@
Module netmiko.base_connection
source = {}
# Keys get normalized to lower-case
+ proxy: Optional[paramiko.proxy.ProxyCommand]
if "proxycommand" in source:
proxy = paramiko.ProxyCommand(source["proxycommand"])
elif "proxyjump" in source:
@@ -892,7 +976,7 @@
msg += self.RETURN + str(auth_err)
raise NetmikoAuthenticationException(msg)
- except paramiko.ssh_exception.SSHException as no_session_err:
+ except paramiko.ssh_exception.SSHException as e:
self.paramiko_cleanup()
- if "No existing session" in str(no_session_err):
+ if "No existing session" in str(e):
msg = (
"Paramiko: 'No existing session' error: "
- "try increasing 'conn_timeout' to 10 seconds or larger."
+ "try increasing 'conn_timeout' to 15 seconds or larger."
)
raise NetmikoTimeoutException(msg)
else:
- raise
+ msg = f"""
+A paramiko SSHException occurred during connection creation:
+
+{str(e)}
+
+"""
+ raise NetmikoTimeoutException(msg)
if self.verbose:
print(f"SSH connection established to {self.host}:{self.port}")
@@ -1019,24 +1111,29 @@
Module netmiko.base_connection
self.remote_conn.settimeout(self.blocking_timeout)
if self.keepalive:
+ assert isinstance(self.remote_conn.transport, paramiko.Transport)
self.remote_conn.transport.set_keepalive(self.keepalive)
+
+ # Migrating communication to channel class
+ self.channel = SSHChannel(conn=self.remote_conn, encoding=self.encoding)
+
self.special_login_handler()
if self.verbose:
print("Interactive SSH session established")
- return ""
- # @m_exec_time
- def _test_channel_read(self, count=40, pattern=""):
+ return None
+
+ def _test_channel_read(self, count: int = 40, pattern: str = "") -> str:
"""Try to read the channel (generally post login) verify you receive data back.
:param count: the number of times to check the channel for data
- :type count: int
:param pattern: Regular expression pattern used to determine end of channel read
- :type pattern: str
"""
- def _increment_delay(main_delay, increment=1.1, maximum=8):
+ def _increment_delay(
+ main_delay: float, increment: float = 1.1, maximum: int = 8
+ ) -> float:
"""Increment sleep time to a maximum value."""
main_delay = main_delay * increment
if main_delay >= maximum:
@@ -1045,30 +1142,26 @@
Module netmiko.base_connection
i = 0
delay_factor = self.select_delay_factor(delay_factor=0)
+
+ if pattern:
+ return self.read_until_pattern(pattern=pattern, read_timeout=20)
+
main_delay = delay_factor * 0.1
time.sleep(main_delay * 10)
new_data = ""
while i <= count:
- new_data += self._read_channel_timing()
- if new_data and pattern:
- if re.search(pattern, new_data):
- break
- elif new_data:
- break
- else:
- self.write_channel(self.RETURN)
+ new_data += self.read_channel_timing()
+ if new_data:
+ return new_data
+ self.write_channel(self.RETURN)
main_delay = _increment_delay(main_delay)
time.sleep(main_delay)
i += 1
- # check if data was ever present
- if new_data:
- return new_data
- else:
- raise NetmikoTimeoutException("Timed out waiting for data")
+ raise NetmikoTimeoutException("Timed out waiting for data")
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> paramiko.SSHClient:
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
@@ -1083,7 +1176,7 @@
Module netmiko.base_connection
remote_conn_pre.set_missing_host_key_policy(self.key_policy)
return remote_conn_pre
- def select_delay_factor(self, delay_factor):
+ def select_delay_factor(self, delay_factor: float) -> float:
"""
Choose the greater of delay_factor or self.global_delay_factor (default).
In fast_cli choose the lesser of delay_factor of self.global_delay_factor.
@@ -1102,31 +1195,37 @@
Module netmiko.base_connection
else:
return self.global_delay_factor
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handler for devices like WLC, Extreme ERS that throw up characters prior to login."""
pass
def disable_paging(
- self, command="terminal length 0", delay_factor=1, cmd_verify=True, pattern=None
- ):
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Disable paging default to a Cisco CLI method.
:param command: Device command to disable pagination of output
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
command = self.normalize_cmd(command)
log.debug("In disable_paging")
log.debug(f"Command: {command}")
self.write_channel(command)
# Make sure you read until you detect the command echo (avoid getting out of sync)
if cmd_verify and self.global_cmd_verify is not False:
- output = self.read_until_pattern(pattern=re.escape(command.strip()))
+ output = self.read_until_pattern(
+ pattern=re.escape(command.strip()), read_timeout=20
+ )
elif pattern:
- output = self.read_until_pattern(pattern=pattern)
+ output = self.read_until_pattern(pattern=pattern, read_timeout=20)
else:
output = self.read_until_prompt()
log.debug(f"{output}")
@@ -1134,24 +1233,29 @@
Module netmiko.base_connection
return output
def set_terminal_width(
- self, command="", delay_factor=1, cmd_verify=False, pattern=None
- ):
+ self,
+ command: str = "",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = False,
+ pattern: Optional[str] = None,
+ ) -> str:
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
if not command:
return ""
- delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
+
# Avoid cmd_verify here as terminal width must be set before doing cmd_verify
if cmd_verify and self.global_cmd_verify is not False:
output = self.read_until_pattern(pattern=re.escape(command.strip()))
@@ -1168,8 +1272,12 @@
entering/exiting config mode.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+
+ :param pattern: Regular expression pattern to search for in find_prompt() call
"""
- prompt = self.find_prompt(delay_factor=delay_factor)
+ if pattern is None:
+ if pri_prompt_terminator and alt_prompt_terminator:
+ pri_term = re.escape(pri_prompt_terminator)
+ alt_term = re.escape(alt_prompt_terminator)
+ pattern = rf"({pri_term}|{alt_term})"
+ elif pri_prompt_terminator:
+ pattern = re.escape(pri_prompt_terminator)
+ elif alt_prompt_terminator:
+ pattern = re.escape(alt_prompt_terminator)
+
+ if pattern:
+ prompt = self.find_prompt(delay_factor=delay_factor, pattern=pattern)
+ else:
+ prompt = self.find_prompt(delay_factor=delay_factor)
+
if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
raise ValueError(f"Router prompt not found: {repr(prompt)}")
# Strip off trailing terminator
self.base_prompt = prompt[:-1]
return self.base_prompt
- def find_prompt(self, delay_factor=1):
+ def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+ ) -> str:
"""Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
+
+ :param pattern: Regular expression pattern to determine whether prompt is valid
"""
delay_factor = self.select_delay_factor(delay_factor)
+ sleep_time = delay_factor * 0.25
self.clear_buffer()
self.write_channel(self.RETURN)
- sleep_time = delay_factor * 0.1
- time.sleep(sleep_time)
-
- # Initial attempt to get prompt
- prompt = self.read_channel().strip()
- # Check if the only thing you received was a newline
- count = 0
- while count <= 12 and not prompt:
+ if pattern:
+ try:
+ prompt = self.read_until_pattern(pattern=pattern)
+ except ReadTimeout:
+ pass
+ else:
+ # Initial read
+ time.sleep(sleep_time)
prompt = self.read_channel().strip()
- if not prompt:
- self.write_channel(self.RETURN)
- time.sleep(sleep_time)
- if sleep_time <= 3:
- # Double the sleep_time when it is small
- sleep_time *= 2
- else:
- sleep_time += 1
- count += 1
+
+ count = 0
+ while count <= 12 and not prompt:
+ if not prompt:
+ self.write_channel(self.RETURN)
+ time.sleep(sleep_time)
+ prompt = self.read_channel().strip()
+ if sleep_time <= 3:
+ # Double the sleep_time when it is small
+ sleep_time *= 2
+ else:
+ sleep_time += 1
+ count += 1
# If multiple lines in the output take the last line
- prompt = self.normalize_linefeeds(prompt)
prompt = prompt.split(self.RESPONSE_RETURN)[-1]
prompt = prompt.strip()
+ self.clear_buffer()
if not prompt:
raise ValueError(f"Unable to find prompt: {prompt}")
- time.sleep(delay_factor * 0.1)
- self.clear_buffer()
log.debug(f"[find_prompt()]: prompt is {prompt}")
return prompt
- def clear_buffer(self, backoff=True):
+ def clear_buffer(
+ self,
+ backoff: bool = True,
+ backoff_max: float = 3.0,
+ delay_factor: Optional[float] = None,
+ ) -> str:
"""Read any data available in the channel."""
- sleep_time = 0.1 * self.global_delay_factor
+
+ if delay_factor is None:
+ delay_factor = self.global_delay_factor
+ sleep_time = 0.1 * delay_factor
+
+ output = ""
for _ in range(10):
time.sleep(sleep_time)
data = self.read_channel()
+ data = self.strip_ansi_escape_codes(data)
+ output += data
if not data:
break
# Double sleep time each time we detect data
log.debug("Clear buffer detects data in the channel")
if backoff:
sleep_time *= 2
- sleep_time = 3 if sleep_time >= 3 else sleep_time
+ sleep_time = backoff_max if sleep_time >= backoff_max else sleep_time
+ return output
+
+ def command_echo_read(self, cmd: str, read_timeout: float) -> str:
+
+ # Make sure you read until you detect the command echo (avoid getting out of sync)
+ new_data = self.read_until_pattern(
+ pattern=re.escape(cmd), read_timeout=read_timeout
+ )
+
+ # There can be echoed prompts that haven't been cleared before the cmd echo
+ # this can later mess up the trailing prompt pattern detection. Clear this out.
+ lines = new_data.split(cmd)
+ if len(lines) == 2:
+ # lines[-1] should realistically just be the null string
+ new_data = f"{cmd}{lines[-1]}"
+ else:
+ # cmd exists in the output multiple times? Just retain the original output
+ pass
+ return new_data
@select_cmd_verify
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,
- ):
+ command_string: str,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = False,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type use_textfsm: 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).
- :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).
- :type cmd_verify: bool
-
- :param cmd_echo: Deprecated (use cmd_verify instead)
- :type cmd_echo: bool
"""
-
- # For compatibility; remove cmd_echo in Netmiko 4.x.x
- if cmd_echo is not None:
- cmd_verify = cmd_echo
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
output = ""
- delay_factor = self.select_delay_factor(delay_factor)
-
+ new_data = ""
if normalize:
command_string = self.normalize_cmd(command_string)
self.write_channel(command_string)
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
-
- # Strip off everything before the command echo
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- output = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
- else:
- # cmd is in the actual output (not just echoed)
- output = new_data
-
- log.debug(f"send_command_timing current output: {output}")
-
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
+ output += new_data
+ output += self.read_channel_timing(
+ last_read=last_read, read_timeout=read_timeout
)
+
output = self._sanitize_output(
output,
strip_command=strip_command,
command_string=command_string,
strip_prompt=strip_prompt,
)
+ return_data = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
+ )
+ return return_data
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
-
- log.debug(f"send_command_timing final output: {output}")
+ def _send_command_timing_str(self, *args: Any, **kwargs: Any) -> str:
+ """Wrapper for `send_command_timing` method that always returns a
+ string"""
+ output = self.send_command_timing(*args, **kwargs)
+ assert isinstance(output, str)
return output
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
:param a_string: Returned string from device
@@ -1388,12 +1506,13 @@
Module netmiko.base_connection
"""
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
+
if self.base_prompt in last_line:
return self.RESPONSE_RETURN.join(response_list[:-1])
else:
return a_string
- def _first_line_handler(self, data, search_pattern):
+ def _first_line_handler(self, data: str, search_pattern: str) -> Tuple[str, bool]:
"""
In certain situations the first line will get repainted which causes a false
match on the terminating pattern.
@@ -1420,126 +1539,151 @@
Module netmiko.base_connection
except IndexError:
return (data, False)
+ def _prompt_handler(self, auto_find_prompt: bool) -> str:
+ if auto_find_prompt:
+ try:
+ prompt = self.find_prompt()
+ except ValueError:
+ prompt = self.base_prompt
+ else:
+ prompt = self.base_prompt
+ return re.escape(prompt.strip())
+
@select_cmd_verify
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,
- ):
+ command_string: str,
+ expect_string: Optional[str] = None,
+ read_timeout: float = 10.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ auto_find_prompt: bool = True,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = True,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a pattern-based mechanism. Generally
used for show commands. By default this method will keep waiting to receive data until the
network device prompt is detected. The current network device prompt will be determined
automatically.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
:param expect_string: Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
- :type expect_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type normalize: bool
: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).
- :type cmd_verify: bool
"""
# Time to delay in each read loop
- loop_delay = 0.2
+ loop_delay = 0.025
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 500:
- # Default arguments are being used; use self.timeout instead
- max_loops = int(self.timeout / loop_delay)
-
- # Find the current router prompt
- if expect_string is None:
- if auto_find_prompt:
- try:
- prompt = self.find_prompt(delay_factor=delay_factor)
- except ValueError:
- prompt = self.base_prompt
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ if self.delay_factor_compat:
+ # For compatibility calculate the old equivalent read_timeout
+ # i.e. what it would have been in Netmiko 3.x
+ if delay_factor is None:
+ tmp_delay_factor = self.global_delay_factor
else:
- prompt = self.base_prompt
- search_pattern = re.escape(prompt.strip())
+ tmp_delay_factor = self.select_delay_factor(delay_factor)
+ compat_timeout = calc_old_timeout(
+ max_loops=max_loops,
+ delay_factor=tmp_delay_factor,
+ loop_delay=0.2,
+ old_timeout=self.timeout,
+ )
+ msg = f"""\n
+You have chosen to use Netmiko's delay_factor compatibility mode for
+send_command. This will revert Netmiko to behave similarly to how it
+did in Netmiko 3.x (i.e. to use delay_factor/global_delay_factor and
+max_loops).
+
+Using these parameters Netmiko has calculated an effective read_timeout
+of {compat_timeout} and will set the read_timeout to this value.
+
+Please convert your code to that new format i.e.:
+
+ net_connect.send_command(cmd, read_timeout={compat_timeout})
+
+And then disable delay_factor_compat.
+
+delay_factor_compat will be removed in Netmiko 5.x.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ # Override the read_timeout with Netmiko 3.x way :-(
+ read_timeout = compat_timeout
+
else:
+ # No need for two deprecation messages so only display this if not using
+ # delay_factor_compat
+ if delay_factor is not None or max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of delay_factor/max_loops with
+send_command. You should convert all uses of delay_factor and max_loops
+over to read_timeout=x where x is the total number of seconds to wait
+before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if expect_string is not None:
search_pattern = expect_string
+ else:
+ search_pattern = self._prompt_handler(auto_find_prompt)
if normalize:
command_string = self.normalize_cmd(command_string)
- time.sleep(delay_factor * loop_delay)
- self.clear_buffer()
+ # Start the clock
+ start_time = time.time()
self.write_channel(command_string)
new_data = ""
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
- # Strip off everything before the command echo (to avoid false positives on the prompt)
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- new_data = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
- i = 1
+ MAX_CHARS = 2_000_000
+ DEQUE_SIZE = 20
output = ""
- past_three_reads = deque(maxlen=3)
+ # Check only the past N-reads. This is for the case where the output is
+ # very large (i.e. searching a very large string for a pattern a whole bunch of times)
+ past_n_reads: Deque[str] = deque(maxlen=DEQUE_SIZE)
first_line_processed = False
- # Keep reading data until search_pattern is found or until max_loops is reached.
- while i <= max_loops:
+ # Keep reading data until search_pattern is found or until read_timeout
+ while time.time() - start_time < read_timeout:
if new_data:
output += new_data
- past_three_reads.append(new_data)
+ past_n_reads.append(new_data)
# Case where we haven't processed the first_line yet (there is a potential issue
# in the first line (in cases where the line is repainted).
@@ -1552,19 +1696,30 @@
Module netmiko.base_connection
break
else:
- # Check if pattern is in the past three reads
- if re.search(search_pattern, "".join(past_three_reads)):
- break
-
- time.sleep(delay_factor * loop_delay)
- i += 1
+ if len(output) <= MAX_CHARS:
+ if re.search(search_pattern, output):
+ break
+ else:
+ # Switch to deque mode if output is greater than MAX_CHARS
+ # Check if pattern is in the past n reads
+ if re.search(search_pattern, "".join(past_n_reads)):
+ break
+
+ time.sleep(loop_delay)
new_data = self.read_channel()
+
else: # nobreak
- raise IOError(
- "Search pattern never detected in send_command: {}".format(
- search_pattern
- )
- )
+ msg = f"""
+Pattern not detected: {repr(search_pattern)} in output.
+
+Things you might try to fix this:
+1. Explicitly set your pattern using the expect_string argument.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.
+
+"""
+ raise ReadTimeout(msg)
output = self._sanitize_output(
output,
@@ -1572,45 +1727,98 @@
Module netmiko.base_connection
command_string=command_string,
strip_prompt=strip_prompt,
)
+ return_val = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
+ )
+ return return_val
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
+ def _send_command_str(self, *args: Any, **kwargs: Any) -> str:
+ """Wrapper for `send_command` method that always returns a string"""
+ output = self.send_command(*args, **kwargs)
+ assert isinstance(output, str)
return output
- def send_command_expect(self, *args, **kwargs):
- """Support previous name of send_command method.
+ def send_command_expect(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """Support previous name of send_command method."""
+ return self.send_command(*args, **kwargs)
- :param args: Positional arguments to send to send_command()
- :type args: list
+ def _multiline_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
+ strip_prompt = kwargs.get("strip_prompt", False)
+ kwargs["strip_prompt"] = strip_prompt
+ strip_command = kwargs.get("strip_command", False)
+ kwargs["strip_command"] = strip_command
+ return kwargs
- :param kwargs: Keyword arguments to send to send_command()
- :type kwargs: dict
+ def send_multiline(
+ self,
+ commands: Sequence[Union[str, List[str]]],
+ multiline: bool = True,
+ **kwargs: Any,
+ ) -> str:
"""
- return self.send_command(*args, **kwargs)
+ commands should either be:
+
+ commands = [[cmd1, expect1], [cmd2, expect2], ...]]
+
+ Or
+
+ commands = [cmd1, cmd2, cmd3, ...]
+
+ Any expect_string that is a null-string will use pattern based on
+ device's prompt (unless expect_string argument is passed in via
+ kwargs.
+
+ """
+ output = ""
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+
+ default_expect_string = kwargs.pop("expect_string", None)
+ if not default_expect_string:
+ auto_find_prompt = kwargs.get("auto_find_prompt", True)
+ default_expect_string = self._prompt_handler(auto_find_prompt)
+
+ if commands and isinstance(commands[0], str):
+ # If list of commands just send directly using default_expect_string (probably prompt)
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_str(
+ cmd, expect_string=default_expect_string, **kwargs
+ )
+ else:
+ # If list of lists, then first element is cmd and second element is expect_string
+ for cmd_item in commands:
+ assert not isinstance(cmd_item, str)
+ cmd, expect_string = cmd_item
+ if not expect_string:
+ expect_string = default_expect_string
+ output += self._send_command_str(
+ cmd, expect_string=expect_string, **kwargs
+ )
+ return output
+
+ def send_multiline_timing(
+ self, commands: Sequence[str], multiline: bool = True, **kwargs: Any
+ ) -> str:
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+ output = ""
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_timing_str(cmd, **kwargs)
+ return output
@staticmethod
- def strip_backspaces(output):
+ def strip_backspaces(output: str) -> str:
"""Strip any backspace characters out of the output.
:param output: Output obtained from a remote network device.
@@ -1619,7 +1827,7 @@
# command_string isn't there; do nothing
return output
- def normalize_linefeeds(self, a_string):
+ def normalize_linefeeds(self, a_string: str) -> str:
"""Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
:param a_string: A string that may have non-normalized line feeds
@@ -1663,7 +1871,7 @@
Module netmiko.base_connection
else:
return a_string
- def normalize_cmd(self, command):
+ def normalize_cmd(self, command: str) -> str:
"""Normalize CLI commands to have a single trailing newline.
:param command: Command that may require line feed to be normalized
@@ -1673,32 +1881,32 @@
Module netmiko.base_connection
command += self.RETURN
return command
- def check_enable_mode(self, check_string=""):
+ def check_enable_mode(self, check_string: str = "") -> bool:
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
"""
self.write_channel(self.RETURN)
- output = self.read_until_prompt()
+ output = self.read_until_prompt(read_entire_line=True)
return check_string in output
def enable(
- self, cmd="", pattern="ssword", enable_pattern=None, re_flags=re.IGNORECASE
- ):
+ self,
+ cmd: str = "",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
"""Enter enable mode.
:param cmd: Device command to enter enable mode
- :type cmd: str
:param pattern: pattern to search for indicating device is waiting for password
- :type pattern: str
:param enable_pattern: pattern indicating you have entered enable mode
- :type pattern: str
:param re_flags: Regular expression flags used in conjunction with pattern
- :type re_flags: int
"""
output = ""
msg = (
@@ -1737,7 +1945,7 @@
Automatically exits/enters configuration mode.
:param config_commands: Multiple configuration commands to be sent to the device
- :type config_commands: list or string
:param exit_config_mode: Determines whether or not to exit config mode after complete
- :type exit_config_mode: bool
- :param delay_factor: Factor to adjust delays
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor (default: 150)
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Determines whether or not to strip the prompt
- :type strip_prompt: bool
:param strip_command: Determines whether or not to strip the command
- :type strip_command: bool
+
+ :param read_timeout: Absolute timer to send to read_channel_timing. Should be rarely needed.
:param config_mode_command: The command to enter into config mode
- :type config_mode_command: str
:param cmd_verify: Whether or not to verify command echo for each command in config_set
- :type cmd_verify: bool
:param enter_config_mode: Do you enter config mode before sending config commands
- :type exit_config_mode: bool
:param error_pattern: Regular expression pattern to detect config errors in the
output.
- :type error_pattern: str
+
+ :param terminator: Regular expression pattern to use as an alternate terminator in certain
+ situations.
+
+ :param bypass_commands: Regular expression pattern indicating configuration commands
+ where cmd_verify is automatically disabled.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if self.global_cmd_verify is not None:
+ cmd_verify = self.global_cmd_verify
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ # Calculate an equivalent read_timeout (if using old settings)
+ # Eliminate in Netmiko 5.x
+ if read_timeout is None:
+ max_loops = 150 if max_loops is None else max_loops
+ delay_factor = 1.0 if delay_factor is None else delay_factor
+
+ # If delay_factor has been set, then look at global_delay_factor
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ read_timeout = calc_old_timeout(
+ max_loops=max_loops, delay_factor=delay_factor, loop_delay=0.1
+ )
+
+ if delay_factor is None:
+ delay_factor = self.select_delay_factor(0)
+ else:
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ if read_timeout is None:
+ read_timeout = 15
+ else:
+ read_timeout = read_timeout
+
if config_commands is None:
return ""
elif isinstance(config_commands, str):
@@ -1897,20 +2143,33 @@
Module netmiko.base_connection
if not hasattr(config_commands, "__iter__"):
raise ValueError("Invalid argument passed into send_config_set")
+ if bypass_commands is None:
+ # Commands where cmd_verify is automatically disabled reg-ex logical-or
+ bypass_commands = r"^banner .*$"
+
+ # Set bypass_commands="" to force no-bypass (usually for testing)
+ bypass_detected = False
+ if bypass_commands:
+ bypass_detected = any(
+ [True for cmd in config_commands if re.search(bypass_commands, cmd)]
+ )
+ if bypass_detected:
+ cmd_verify = False
+
# Send config commands
output = ""
if enter_config_mode:
- cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
- output += self.config_mode(*cfg_mode_args)
+ if config_mode_command:
+ output += self.config_mode(config_mode_command)
+ else:
+ output += self.config_mode()
- # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ # Perform output gathering line-by-line (legacy way)
if self.fast_cli and self._legacy_mode and not error_pattern:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
elif not cmd_verify:
for cmd in config_commands:
@@ -1919,35 +2178,25 @@
Module netmiko.base_connection
# Gather the output incrementally due to error_pattern requirements
if error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
if re.search(error_pattern, output, flags=re.M):
msg = f"Invalid input detected at command: {cmd}"
raise ConfigInvalidException(msg)
# Standard output gathering (no error_pattern)
if not error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Make sure command is echoed
- new_output = self.read_until_pattern(pattern=re.escape(cmd.strip()))
- output += new_output
-
- # We might capture next prompt in the original read
- pattern = f"(?:{re.escape(self.base_prompt)}|#)"
- if not re.search(pattern, new_output):
- # Make sure trailing prompt comes back (after command)
- # NX-OS has fast-buffering problem where it immediately echoes command
- # Even though the device hasn't caught up with processing command.
- new_output = self.read_until_pattern(pattern=pattern)
- output += new_output
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+
+ # Read until next prompt or terminator (#); the .*$ forces read of entire line
+ pattern = f"(?:{re.escape(self.base_prompt)}.*$|{terminator}.*$)"
+ output += self.read_until_pattern(pattern=pattern, re_flags=re.M)
if error_pattern:
if re.search(error_pattern, output, flags=re.M):
@@ -1960,7 +2209,7 @@
Module netmiko.base_connection
log.debug(f"{output}")
return output
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Remove any ANSI (VT100) ESC codes from the output
@@ -1981,10 +2230,11 @@
Module netmiko.base_connection
ESC[?6l Reset mode screen with options 640 x 200 monochrome (graphics)
ESC[?7l Disable line wrapping
ESC[2J Code erase display
- ESC[00;32m Color Green (30 to 37 are different colors) more general pattern is
- ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+ ESC[00;32m Color Green (30 to 37 are different colors)
ESC[6n Get cursor position
ESC[1D Move cursor position leftward by x characters (1 in this case)
+ ESC[9999B Move cursor down N-lines (very large value is attempt to move to the
+ very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
@@ -2006,7 +2256,8 @@
return output
- def cleanup(self, command=""):
+ def cleanup(self, command: str = "") -> None:
"""Logout of the session on the network device plus any additional cleanup."""
pass
- def paramiko_cleanup(self):
+ def paramiko_cleanup(self) -> None:
"""Cleanup Paramiko to try to gracefully handle SSH session ending."""
- self.remote_conn_pre.close()
+ if self.remote_conn_pre is not None:
+ self.remote_conn_pre.close()
del self.remote_conn_pre
- def disconnect(self):
+ def disconnect(self) -> None:
"""Try to gracefully close the session."""
try:
self.cleanup()
if self.protocol == "ssh":
self.paramiko_cleanup()
elif self.protocol == "telnet":
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
self.remote_conn.close()
elif self.protocol == "serial":
+ assert isinstance(self.remote_conn, serial.Serial)
self.remote_conn.close()
except Exception:
# There have been race conditions observed on disconnect.
@@ -2082,31 +2347,25 @@
Module netmiko.base_connection
finally:
self.remote_conn_pre = None
self.remote_conn = None
- self.close_session_log()
+ if self.session_log:
+ self.session_log.close()
- def commit(self):
+ def commit(self) -> str:
"""Commit method for platforms that support this."""
raise AttributeError("Network device does not support 'commit()' method")
- def save_config(self, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
- def open_session_log(self, filename, mode="write"):
- """Open the session_log file."""
- if mode == "append":
- self.session_log = open(filename, mode="a", encoding=self.encoding)
- else:
- self.session_log = open(filename, mode="w", encoding=self.encoding)
- self._session_log_close = True
-
- def close_session_log(self):
- """Close the session_log file (if it is a file that we opened)."""
- if self.session_log is not None and self._session_log_close:
- self.session_log.close()
- self.session_log = None
-
- def run_ttp(self, template, res_kwargs={}, **kwargs):
+ def run_ttp(
+ self,
+ template: Union[str, bytes, "PathLike[Any]"],
+ res_kwargs: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Any:
"""
Run TTP template parsing by using input parameters to collect
devices output.
@@ -2114,29 +2373,25 @@
Module netmiko.base_connection
:param template: template content, OS path to template or reference
to template within TTP templates collection in
ttp://path/to/template.txt format
- :type template: str
:param res_kwargs: ``**res_kwargs`` arguments to pass to TTP result method
- :type res_kwargs: dict
:param kwargs: any other ``**kwargs`` to use for TTP object instantiation
- :type kwargs: dict
TTP template must have inputs defined together with below parameters.
:param method: name of Netmiko connection object method to call, default ``send_command``
- :type method: str
:param kwargs: Netmiko connection object method arguments
- :type kwargs: dict
:param commands: list of commands to collect
- :type commands: list
Inputs' load could be of one of the supported formats and controlled by input's ``load``
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
"""
+ if res_kwargs is None:
+ res_kwargs = {}
return run_ttp_template(
connection=self, template=template, res_kwargs=res_kwargs, **kwargs
)
@@ -2151,13 +2406,67 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
else:
self.protocol = "ssh"
+ self.key_policy: paramiko.client.MissingHostKeyPolicy
if not ssh_strict:
self.key_policy = paramiko.AutoAddPolicy()
else:
@@ -2597,6 +2877,7 @@
Classes
self.system_host_keys = system_host_keys
self.alt_host_keys = alt_host_keys
self.alt_key_file = alt_key_file
+ self.disabled_algorithms = disabled_algorithms or {}
# For SSH proxy support
self.ssh_config_file = ssh_config_file
@@ -2605,25 +2886,30 @@
Classes
if auto_connect:
self._open()
- def _open(self):
+ def _open(self) -> None:
"""Decouple connection creation from __init__ for mocking."""
self._modify_connection_params()
self.establish_connection()
self._try_session_preparation()
- def __enter__(self):
+ def __enter__(self) -> "BaseConnection":
"""Establish a session using a Context Manager."""
return self
- def __exit__(self, exc_type, exc_value, traceback):
+ def __exit__(
+ self,
+ exc_type: Optional[Type[BaseException]],
+ exc_value: Optional[BaseException],
+ traceback: Optional[TracebackType],
+ ) -> None:
"""Gracefully close connection on Context Manager exit."""
self.disconnect()
- def _modify_connection_params(self):
+ def _modify_connection_params(self) -> None:
"""Modify connection parameters prior to SSH connection."""
pass
- def _timeout_exceeded(self, start, msg="Timeout exceeded!"):
+ def _timeout_exceeded(self, start: float, msg: str = "Timeout exceeded!") -> bool:
"""Raise NetmikoTimeoutException if waiting too much in the serving queue.
:param start: Initial start time to see if session lock timeout has been exceeded
@@ -2640,7 +2926,7 @@
Classes
raise NetmikoTimeoutException(msg)
return False
- def _lock_netmiko_session(self, start=None):
+ def _lock_netmiko_session(self, start: Optional[float] = None) -> bool:
"""Try to acquire the Netmiko session lock. If not available, wait in the queue until
the channel is available again.
@@ -2656,68 +2942,33 @@
Classes
time.sleep(0.1)
return True
- def _unlock_netmiko_session(self):
+ def _unlock_netmiko_session(self) -> None:
"""
Release the channel at the end of the task.
"""
if self._session_locker.locked():
self._session_locker.release()
- def _write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+ def _autodetect_fs(self, cmd: str = "", pattern: str = "") -> str:
+ raise NotImplementedError
- :param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
- """
- if self.protocol == "ssh":
- self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))
- elif self.protocol == "telnet":
- self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
- elif self.protocol == "serial":
- self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
- self.remote_conn.flush()
- else:
- raise ValueError("Invalid protocol specified")
- try:
- log.debug(
- "write_channel: {}".format(
- write_bytes(out_data, encoding=self.encoding)
- )
- )
- if self._session_log_fin or self.session_log_record_writes:
- self._write_session_log(out_data)
- except UnicodeDecodeError:
- # Don't log non-ASCII characters; this is null characters and telnet IAC (PY2)
- pass
+ def _enter_shell(self) -> str:
+ raise NotImplementedError
- def _write_session_log(self, data):
- if self.session_log is not None and len(data) > 0:
- # Hide the password and secret in the session_log
- if self.password:
- data = data.replace(self.password, "********")
- if self.secret:
- data = data.replace(self.secret, "********")
- if isinstance(self.session_log, io.BufferedIOBase):
- data = self.normalize_linefeeds(data)
- self.session_log.write(write_bytes(data, encoding=self.encoding))
- else:
- self.session_log.write(self.normalize_linefeeds(data))
- self.session_log.flush()
+ def _return_cli(self) -> str:
+ raise NotImplementedError
- def write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+ @lock_channel
+ @log_writes
+ def write_channel(self, out_data: str) -> None:
+ """Generic method that will write data out the channel.
:param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
+ :type out_data: str
"""
- self._lock_netmiko_session()
- try:
- self._write_channel(out_data)
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+ self.channel.write_channel(out_data)
- def is_alive(self):
+ def is_alive(self) -> bool:
"""Returns a boolean flag with the state of the connection."""
null = chr(0)
if self.remote_conn is None:
@@ -2729,9 +2980,11 @@
Classes
# IAC = Interpret as Command; it comes before the NOP.
log.debug("Sending IAC + NOP")
# Need to send multiple times to test connection
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
+ telnet_socket = self.remote_conn.get_socket()
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
return True
except AttributeError:
return False
@@ -2741,203 +2994,236 @@
Classes
# Try sending ASCII null byte to maintain the connection alive
log.debug("Sending the NULL byte")
self.write_channel(null)
- return self.remote_conn.transport.is_active()
+ assert isinstance(self.remote_conn, paramiko.Channel)
+ assert self.remote_conn.transport is not None
+ result = self.remote_conn.transport.is_active()
+ assert isinstance(result, bool)
+ return result
except (socket.error, EOFError):
log.error("Unable to send", exc_info=True)
# If unable to send, we can tell for sure that the connection is unusable
return False
return False
- def _read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- if self.protocol == "ssh":
- output = ""
- while True:
- if self.remote_conn.recv_ready():
- outbuf = self.remote_conn.recv(MAX_BUFFER)
- if len(outbuf) == 0:
- raise EOFError("Channel stream closed by remote device.")
- output += outbuf.decode("utf-8", "ignore")
- else:
- break
- elif self.protocol == "telnet":
- output = self.remote_conn.read_very_eager().decode("utf-8", "ignore")
- elif self.protocol == "serial":
- output = ""
- while self.remote_conn.in_waiting > 0:
- output += self.remote_conn.read(self.remote_conn.in_waiting).decode(
- "utf-8", "ignore"
- )
+ @lock_channel
+ def read_channel(self) -> str:
+ """Generic handler that will read all the data from given channel."""
+ new_data = self.channel.read_channel()
+ new_data = self.normalize_linefeeds(new_data)
if self.ansi_escape_codes:
- output = self.strip_ansi_escape_codes(output)
- log.debug(f"read_channel: {output}")
- self._write_session_log(output)
+ new_data = self.strip_ansi_escape_codes(new_data)
+ log.debug(f"read_channel: {new_data}")
+ if self.session_log:
+ self.session_log.write(new_data)
+
+ # If data had been previously saved to the buffer, the prepend it to output
+ # do post read_channel so session_log/log doesn't record buffered data twice
+ if self._read_buffer:
+ output = self._read_buffer + new_data
+ self._read_buffer = ""
+ else:
+ output = new_data
return output
- def read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- output = ""
- self._lock_netmiko_session()
- try:
- output = self._read_channel()
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
- return output
+ def read_until_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel until pattern is detected.
- def _read_channel_expect(self, pattern="", re_flags=0, max_loops=150):
- """Function that reads channel until pattern is detected.
+ Will return string up to and including pattern.
- pattern takes a regular expression.
+ Returns ReadTimeout if pattern not detected in read_timeout seconds.
- By default pattern will be self.base_prompt
+ :param pattern: Regular expression pattern used to identify that reading is done.
- Note: this currently reads beyond pattern. In the case of SSH it reads MAX_BUFFER.
- In the case of telnet it reads all non-blocking data.
+ :param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+ A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+ reading indefinitely until pattern is detected.
- There are dependencies here like determining whether in config_mode that are actually
- depending on reading beyond pattern.
+ :param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
- :param pattern: Regular expression pattern used to identify the command is done \
- (defaults to self.base_prompt)
- :type pattern: str (regular expression)
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of max_loops with read_until_pattern.
+You should convert all uses of max_loops over to read_timeout=x
+where x is the total number of seconds to wait before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
- :param max_loops: max number of iterations to read the channel before raising exception.
- Will default to be based upon self.timeout.
- :type max_loops: int
- """
output = ""
- if not pattern:
- pattern = re.escape(self.base_prompt)
- log.debug(f"Pattern is: {pattern}")
-
- i = 1
- loop_delay = 0.1
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # argument for backwards compatibility).
- if max_loops == 150:
- max_loops = int(self.timeout / loop_delay)
- while i < max_loops:
- if self.protocol == "ssh":
- try:
- # If no data available will wait timeout seconds trying to read
- self._lock_netmiko_session()
- new_data = self.remote_conn.recv(MAX_BUFFER)
- if len(new_data) == 0:
- raise EOFError("Channel stream closed by remote device.")
- new_data = new_data.decode("utf-8", "ignore")
- if self.ansi_escape_codes:
- new_data = self.strip_ansi_escape_codes(new_data)
- log.debug(f"_read_channel_expect read_data: {new_data}")
- output += new_data
- self._write_session_log(new_data)
- except socket.timeout:
- raise NetmikoTimeoutException(
- "Timed-out reading channel, data not available."
- )
- finally:
- self._unlock_netmiko_session()
- elif self.protocol == "telnet" or "serial":
- output += self.read_channel()
+ loop_delay = 0.01
+ start_time = time.time()
+ # if read_timeout == 0 or 0.0 keep reading indefinitely
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ output += self.read_channel()
if re.search(pattern, output, flags=re_flags):
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ # The string matched by pattern must be retained in the output string.
+ # re.split will do this if capturing parentesis are used.
+ if len(results) == 2:
+ # no capturing parenthesis, convert and try again.
+ pattern = f"({pattern})"
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ if len(results) != 3:
+ # well, we tried
+ msg = f"""Unable to successfully split output based on pattern:
+pattern={pattern}
+output={repr(output)}
+results={results}
+"""
+ raise ReadException(msg)
+
+ # Process such that everything before and including pattern is return.
+ # Everything else is retained in the _read_buffer
+ output, match_str, buffer = results
+ output = output + match_str
+ if buffer:
+ self._read_buffer += buffer
log.debug(f"Pattern found: {pattern} {output}")
return output
- time.sleep(loop_delay * self.global_delay_factor)
- i += 1
- raise NetmikoTimeoutException(
- f"Timed-out reading channel, pattern not found in output: {pattern}"
- )
+ time.sleep(loop_delay)
+
+ msg = f"""\n\nPattern not detected: {repr(pattern)} in output.
- def _read_channel_timing(self, delay_factor=1, max_loops=150):
+Things you might try to fix this:
+1. Adjust the regex pattern to better identify the terminating string. Note, in
+many situations the pattern is automatically based on the network device's prompt.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.\n\n"""
+ raise ReadTimeout(msg)
+
+ def read_channel_timing(
+ self,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ ) -> str:
"""Read data on the channel based on timing delays.
- Attempt to read channel max_loops number of times. If no data this will cause a 15 second
- delay.
+ General pattern is keep reading until no new data is read.
+ Once no new data is read wait `last_read` amount of time (one last read).
+ As long as no new data, then return data.
+
+ `read_timeout` is an absolute timer for how long to keep reading (which presupposes
+ we are still getting new data).
- Once data is encountered read channel for another two seconds (2 * delay_factor) to make
- sure reading of channel is complete.
+ Setting `read_timeout` to zero will cause read_channel_timing to never expire based
+ on an absolute timeout. It will only complete based on timeout based on their being
+ no new data.
- :param delay_factor: multiplicative factor to adjust delay when reading channel (delays
- get multiplied by this factor)
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: maximum number of loops to iterate through before returning channel data.
- Will default to be based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
- # Time to delay in each read loop
- loop_delay = 0.1
- final_delay = 2
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 150:
- max_loops = int(self.timeout / loop_delay)
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
- # FIX: Cleanup in future versions of Netmiko
- if delay_factor < 1:
- if not self._legacy_mode and self.fast_cli:
- delay_factor = 1
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+ # Time to delay in each read loop
+ loop_delay = 0.1
channel_data = ""
- i = 0
- while i <= max_loops:
- time.sleep(loop_delay * delay_factor)
+ start_time = time.time()
+
+ # Set read_timeout to 0 to never timeout
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ time.sleep(loop_delay)
new_data = self.read_channel()
+ # gather new output
if new_data:
channel_data += new_data
- else:
- # Safeguard to make sure really done
- time.sleep(final_delay * delay_factor)
+ # if we have some output, but nothing new, then do the last read
+ elif channel_data != "":
+ # Make sure really done (i.e. no new data)
+ time.sleep(last_read)
new_data = self.read_channel()
if not new_data:
break
else:
channel_data += new_data
- i += 1
- return channel_data
+ else:
+ msg = f"""\n
+read_channel_timing's absolute timer expired.
- def read_until_prompt(self, *args, **kwargs):
- """Read channel until self.base_prompt detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+The network device was continually outputting data for longer than {read_timeout}
+seconds.
- def read_until_pattern(self, *args, **kwargs):
- """Read channel until pattern detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+If this is expected i.e. the command you are executing is continually emitting
+data for a long period of time, then you can set 'read_timeout=x' seconds. If
+you want Netmiko to keep reading indefinitely (i.e. to only stop when there is
+no new data), then you can set 'read_timeout=0'.
- def read_until_prompt_or_pattern(self, pattern="", re_flags=0):
- """Read until either self.base_prompt or pattern is detected.
+You can look at the Netmiko session_log or debug log for more information.
- :param pattern: the pattern used to identify that the output is complete (i.e. stop \
- reading when pattern is detected). pattern will be combined with self.base_prompt to \
- terminate output reading when the first of self.base_prompt or pattern is detected.
- :type pattern: regular expression string
+"""
+ raise ReadTimeout(msg)
+ return channel_data
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
+ def read_until_prompt(
+ self,
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel up to and including self.base_prompt."""
+ pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ pattern = f"{pattern}.*"
+ return self.read_until_pattern(
+ pattern=pattern,
+ re_flags=re_flags,
+ max_loops=max_loops,
+ read_timeout=read_timeout,
+ )
- """
- combined_pattern = re.escape(self.base_prompt)
+ def read_until_prompt_or_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read until either self.base_prompt or pattern is detected."""
+ prompt_pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ prompt_pattern = f"{prompt_pattern}.*"
if pattern:
- combined_pattern = r"({}|{})".format(combined_pattern, pattern)
- return self._read_channel_expect(combined_pattern, re_flags=re_flags)
+ combined_pattern = r"(?:{}|{})".format(prompt_pattern, pattern)
+ else:
+ combined_pattern = prompt_pattern
+ return self.read_until_pattern(
+ pattern=combined_pattern,
+ re_flags=re_flags,
+ max_loops=max_loops,
+ read_timeout=read_timeout,
+ )
def serial_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:[Uu]ser:|sername|ogin)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
- self.telnet_login(
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:[Uu]ser:|sername|ogin)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
+ return self.telnet_login(
pri_prompt_terminator,
alt_prompt_terminator,
username_pattern,
@@ -2948,33 +3234,28 @@
Classes
def telnet_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
"""Telnet login. Can be username/password or just password.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param username_pattern: Pattern used to identify the username prompt
- :type username_pattern: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
:param max_loops: Controls the wait time in conjunction with the delay_factor
- (default: 20)
"""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
+ # Revert telnet_login back to old speeds/delays
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -3000,6 +3281,7 @@
Classes
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -3019,6 +3301,7 @@
Classes
time.sleep(0.5 * delay_factor)
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -3034,10 +3317,11 @@
Classes
return return_msg
msg = f"Login failed: {self.host}"
+ assert self.remote_conn is not None
self.remote_conn.close()
raise NetmikoAuthenticationException(msg)
- def _try_session_preparation(self):
+ def _try_session_preparation(self) -> None:
"""
In case of an exception happening during `session_preparation()` Netmiko should
gracefully clean-up after itself. This might be challenging for library users
@@ -3050,7 +3334,7 @@
Classes
self.disconnect()
raise
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -3058,31 +3342,27 @@
Classes
early on in the session.
In general, it should include:
- self._test_channel_read()
+ self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
- self.disable_paging()
self.set_terminal_width()
- self.clear_buffer()
+ self.disable_paging()
"""
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def _use_ssh_config(self, dict_arg):
+ def _use_ssh_config(self, dict_arg: Dict[str, Any]) -> Dict[str, Any]:
"""Update SSH connection parameters based on contents of SSH config file.
:param dict_arg: Dictionary of SSH connection parameters
- :type dict_arg: dict
"""
connect_dict = dict_arg.copy()
# Use SSHConfig to generate source content.
+ assert self.ssh_config_file is not None
full_path = path.abspath(path.expanduser(self.ssh_config_file))
+ source: Union[paramiko.config.SSHConfigDict, Dict[str, Any]]
if path.exists(full_path):
ssh_config_instance = paramiko.SSHConfig()
with io.open(full_path, "rt", encoding="utf-8") as f:
@@ -3092,6 +3372,7 @@
Classes
source = {}
# Keys get normalized to lower-case
+ proxy: Optional[paramiko.proxy.ProxyCommand]
if "proxycommand" in source:
proxy = paramiko.ProxyCommand(source["proxycommand"])
elif "proxyjump" in source:
@@ -3120,7 +3401,7 @@
msg += self.RETURN + str(auth_err)
raise NetmikoAuthenticationException(msg)
- except paramiko.ssh_exception.SSHException as no_session_err:
+ except paramiko.ssh_exception.SSHException as e:
self.paramiko_cleanup()
- if "No existing session" in str(no_session_err):
+ if "No existing session" in str(e):
msg = (
"Paramiko: 'No existing session' error: "
- "try increasing 'conn_timeout' to 10 seconds or larger."
+ "try increasing 'conn_timeout' to 15 seconds or larger."
)
raise NetmikoTimeoutException(msg)
else:
- raise
+ msg = f"""
+A paramiko SSHException occurred during connection creation:
+
+{str(e)}
+
+"""
+ raise NetmikoTimeoutException(msg)
if self.verbose:
print(f"SSH connection established to {self.host}:{self.port}")
@@ -3247,24 +3536,29 @@
Classes
self.remote_conn.settimeout(self.blocking_timeout)
if self.keepalive:
+ assert isinstance(self.remote_conn.transport, paramiko.Transport)
self.remote_conn.transport.set_keepalive(self.keepalive)
+
+ # Migrating communication to channel class
+ self.channel = SSHChannel(conn=self.remote_conn, encoding=self.encoding)
+
self.special_login_handler()
if self.verbose:
print("Interactive SSH session established")
- return ""
- # @m_exec_time
- def _test_channel_read(self, count=40, pattern=""):
+ return None
+
+ def _test_channel_read(self, count: int = 40, pattern: str = "") -> str:
"""Try to read the channel (generally post login) verify you receive data back.
:param count: the number of times to check the channel for data
- :type count: int
:param pattern: Regular expression pattern used to determine end of channel read
- :type pattern: str
"""
- def _increment_delay(main_delay, increment=1.1, maximum=8):
+ def _increment_delay(
+ main_delay: float, increment: float = 1.1, maximum: int = 8
+ ) -> float:
"""Increment sleep time to a maximum value."""
main_delay = main_delay * increment
if main_delay >= maximum:
@@ -3273,30 +3567,26 @@
Classes
i = 0
delay_factor = self.select_delay_factor(delay_factor=0)
+
+ if pattern:
+ return self.read_until_pattern(pattern=pattern, read_timeout=20)
+
main_delay = delay_factor * 0.1
time.sleep(main_delay * 10)
new_data = ""
while i <= count:
- new_data += self._read_channel_timing()
- if new_data and pattern:
- if re.search(pattern, new_data):
- break
- elif new_data:
- break
- else:
- self.write_channel(self.RETURN)
+ new_data += self.read_channel_timing()
+ if new_data:
+ return new_data
+ self.write_channel(self.RETURN)
main_delay = _increment_delay(main_delay)
time.sleep(main_delay)
i += 1
- # check if data was ever present
- if new_data:
- return new_data
- else:
- raise NetmikoTimeoutException("Timed out waiting for data")
+ raise NetmikoTimeoutException("Timed out waiting for data")
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> paramiko.SSHClient:
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
@@ -3311,7 +3601,7 @@
Classes
remote_conn_pre.set_missing_host_key_policy(self.key_policy)
return remote_conn_pre
- def select_delay_factor(self, delay_factor):
+ def select_delay_factor(self, delay_factor: float) -> float:
"""
Choose the greater of delay_factor or self.global_delay_factor (default).
In fast_cli choose the lesser of delay_factor of self.global_delay_factor.
@@ -3330,31 +3620,37 @@
Classes
else:
return self.global_delay_factor
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handler for devices like WLC, Extreme ERS that throw up characters prior to login."""
pass
def disable_paging(
- self, command="terminal length 0", delay_factor=1, cmd_verify=True, pattern=None
- ):
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Disable paging default to a Cisco CLI method.
:param command: Device command to disable pagination of output
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
command = self.normalize_cmd(command)
log.debug("In disable_paging")
log.debug(f"Command: {command}")
self.write_channel(command)
# Make sure you read until you detect the command echo (avoid getting out of sync)
if cmd_verify and self.global_cmd_verify is not False:
- output = self.read_until_pattern(pattern=re.escape(command.strip()))
+ output = self.read_until_pattern(
+ pattern=re.escape(command.strip()), read_timeout=20
+ )
elif pattern:
- output = self.read_until_pattern(pattern=pattern)
+ output = self.read_until_pattern(pattern=pattern, read_timeout=20)
else:
output = self.read_until_prompt()
log.debug(f"{output}")
@@ -3362,24 +3658,29 @@
Classes
return output
def set_terminal_width(
- self, command="", delay_factor=1, cmd_verify=False, pattern=None
- ):
+ self,
+ command: str = "",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = False,
+ pattern: Optional[str] = None,
+ ) -> str:
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
if not command:
return ""
- delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
+
# Avoid cmd_verify here as terminal width must be set before doing cmd_verify
if cmd_verify and self.global_cmd_verify is not False:
output = self.read_until_pattern(pattern=re.escape(command.strip()))
@@ -3396,8 +3697,12 @@
entering/exiting config mode.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+
+ :param pattern: Regular expression pattern to search for in find_prompt() call
"""
- prompt = self.find_prompt(delay_factor=delay_factor)
+ if pattern is None:
+ if pri_prompt_terminator and alt_prompt_terminator:
+ pri_term = re.escape(pri_prompt_terminator)
+ alt_term = re.escape(alt_prompt_terminator)
+ pattern = rf"({pri_term}|{alt_term})"
+ elif pri_prompt_terminator:
+ pattern = re.escape(pri_prompt_terminator)
+ elif alt_prompt_terminator:
+ pattern = re.escape(alt_prompt_terminator)
+
+ if pattern:
+ prompt = self.find_prompt(delay_factor=delay_factor, pattern=pattern)
+ else:
+ prompt = self.find_prompt(delay_factor=delay_factor)
+
if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
raise ValueError(f"Router prompt not found: {repr(prompt)}")
# Strip off trailing terminator
self.base_prompt = prompt[:-1]
return self.base_prompt
- def find_prompt(self, delay_factor=1):
+ def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+ ) -> str:
"""Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
+
+ :param pattern: Regular expression pattern to determine whether prompt is valid
"""
delay_factor = self.select_delay_factor(delay_factor)
+ sleep_time = delay_factor * 0.25
self.clear_buffer()
self.write_channel(self.RETURN)
- sleep_time = delay_factor * 0.1
- time.sleep(sleep_time)
-
- # Initial attempt to get prompt
- prompt = self.read_channel().strip()
- # Check if the only thing you received was a newline
- count = 0
- while count <= 12 and not prompt:
+ if pattern:
+ try:
+ prompt = self.read_until_pattern(pattern=pattern)
+ except ReadTimeout:
+ pass
+ else:
+ # Initial read
+ time.sleep(sleep_time)
prompt = self.read_channel().strip()
- if not prompt:
- self.write_channel(self.RETURN)
- time.sleep(sleep_time)
- if sleep_time <= 3:
- # Double the sleep_time when it is small
- sleep_time *= 2
- else:
- sleep_time += 1
- count += 1
+
+ count = 0
+ while count <= 12 and not prompt:
+ if not prompt:
+ self.write_channel(self.RETURN)
+ time.sleep(sleep_time)
+ prompt = self.read_channel().strip()
+ if sleep_time <= 3:
+ # Double the sleep_time when it is small
+ sleep_time *= 2
+ else:
+ sleep_time += 1
+ count += 1
# If multiple lines in the output take the last line
- prompt = self.normalize_linefeeds(prompt)
prompt = prompt.split(self.RESPONSE_RETURN)[-1]
prompt = prompt.strip()
+ self.clear_buffer()
if not prompt:
raise ValueError(f"Unable to find prompt: {prompt}")
- time.sleep(delay_factor * 0.1)
- self.clear_buffer()
log.debug(f"[find_prompt()]: prompt is {prompt}")
return prompt
- def clear_buffer(self, backoff=True):
+ def clear_buffer(
+ self,
+ backoff: bool = True,
+ backoff_max: float = 3.0,
+ delay_factor: Optional[float] = None,
+ ) -> str:
"""Read any data available in the channel."""
- sleep_time = 0.1 * self.global_delay_factor
+
+ if delay_factor is None:
+ delay_factor = self.global_delay_factor
+ sleep_time = 0.1 * delay_factor
+
+ output = ""
for _ in range(10):
time.sleep(sleep_time)
data = self.read_channel()
+ data = self.strip_ansi_escape_codes(data)
+ output += data
if not data:
break
# Double sleep time each time we detect data
log.debug("Clear buffer detects data in the channel")
if backoff:
sleep_time *= 2
- sleep_time = 3 if sleep_time >= 3 else sleep_time
+ sleep_time = backoff_max if sleep_time >= backoff_max else sleep_time
+ return output
+
+ def command_echo_read(self, cmd: str, read_timeout: float) -> str:
+
+ # Make sure you read until you detect the command echo (avoid getting out of sync)
+ new_data = self.read_until_pattern(
+ pattern=re.escape(cmd), read_timeout=read_timeout
+ )
+
+ # There can be echoed prompts that haven't been cleared before the cmd echo
+ # this can later mess up the trailing prompt pattern detection. Clear this out.
+ lines = new_data.split(cmd)
+ if len(lines) == 2:
+ # lines[-1] should realistically just be the null string
+ new_data = f"{cmd}{lines[-1]}"
+ else:
+ # cmd exists in the output multiple times? Just retain the original output
+ pass
+ return new_data
@select_cmd_verify
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,
- ):
+ command_string: str,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = False,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type use_textfsm: 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).
- :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).
- :type cmd_verify: bool
-
- :param cmd_echo: Deprecated (use cmd_verify instead)
- :type cmd_echo: bool
"""
-
- # For compatibility; remove cmd_echo in Netmiko 4.x.x
- if cmd_echo is not None:
- cmd_verify = cmd_echo
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
output = ""
- delay_factor = self.select_delay_factor(delay_factor)
-
+ new_data = ""
if normalize:
command_string = self.normalize_cmd(command_string)
self.write_channel(command_string)
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
-
- # Strip off everything before the command echo
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- output = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
- else:
- # cmd is in the actual output (not just echoed)
- output = new_data
-
- log.debug(f"send_command_timing current output: {output}")
-
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
+ output += new_data
+ output += self.read_channel_timing(
+ last_read=last_read, read_timeout=read_timeout
)
+
output = self._sanitize_output(
output,
strip_command=strip_command,
command_string=command_string,
strip_prompt=strip_prompt,
)
+ return_data = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
+ )
+ return return_data
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
-
- log.debug(f"send_command_timing final output: {output}")
+ def _send_command_timing_str(self, *args: Any, **kwargs: Any) -> str:
+ """Wrapper for `send_command_timing` method that always returns a
+ string"""
+ output = self.send_command_timing(*args, **kwargs)
+ assert isinstance(output, str)
return output
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
:param a_string: Returned string from device
@@ -3616,12 +3931,13 @@
Classes
"""
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
+
if self.base_prompt in last_line:
return self.RESPONSE_RETURN.join(response_list[:-1])
else:
return a_string
- def _first_line_handler(self, data, search_pattern):
+ def _first_line_handler(self, data: str, search_pattern: str) -> Tuple[str, bool]:
"""
In certain situations the first line will get repainted which causes a false
match on the terminating pattern.
@@ -3648,126 +3964,151 @@
Classes
except IndexError:
return (data, False)
+ def _prompt_handler(self, auto_find_prompt: bool) -> str:
+ if auto_find_prompt:
+ try:
+ prompt = self.find_prompt()
+ except ValueError:
+ prompt = self.base_prompt
+ else:
+ prompt = self.base_prompt
+ return re.escape(prompt.strip())
+
@select_cmd_verify
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,
- ):
+ command_string: str,
+ expect_string: Optional[str] = None,
+ read_timeout: float = 10.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ auto_find_prompt: bool = True,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = True,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a pattern-based mechanism. Generally
used for show commands. By default this method will keep waiting to receive data until the
network device prompt is detected. The current network device prompt will be determined
automatically.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
:param expect_string: Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
- :type expect_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type normalize: bool
: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).
- :type cmd_verify: bool
"""
# Time to delay in each read loop
- loop_delay = 0.2
+ loop_delay = 0.025
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 500:
- # Default arguments are being used; use self.timeout instead
- max_loops = int(self.timeout / loop_delay)
-
- # Find the current router prompt
- if expect_string is None:
- if auto_find_prompt:
- try:
- prompt = self.find_prompt(delay_factor=delay_factor)
- except ValueError:
- prompt = self.base_prompt
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ if self.delay_factor_compat:
+ # For compatibility calculate the old equivalent read_timeout
+ # i.e. what it would have been in Netmiko 3.x
+ if delay_factor is None:
+ tmp_delay_factor = self.global_delay_factor
else:
- prompt = self.base_prompt
- search_pattern = re.escape(prompt.strip())
+ tmp_delay_factor = self.select_delay_factor(delay_factor)
+ compat_timeout = calc_old_timeout(
+ max_loops=max_loops,
+ delay_factor=tmp_delay_factor,
+ loop_delay=0.2,
+ old_timeout=self.timeout,
+ )
+ msg = f"""\n
+You have chosen to use Netmiko's delay_factor compatibility mode for
+send_command. This will revert Netmiko to behave similarly to how it
+did in Netmiko 3.x (i.e. to use delay_factor/global_delay_factor and
+max_loops).
+
+Using these parameters Netmiko has calculated an effective read_timeout
+of {compat_timeout} and will set the read_timeout to this value.
+
+Please convert your code to that new format i.e.:
+
+ net_connect.send_command(cmd, read_timeout={compat_timeout})
+
+And then disable delay_factor_compat.
+
+delay_factor_compat will be removed in Netmiko 5.x.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ # Override the read_timeout with Netmiko 3.x way :-(
+ read_timeout = compat_timeout
+
else:
+ # No need for two deprecation messages so only display this if not using
+ # delay_factor_compat
+ if delay_factor is not None or max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of delay_factor/max_loops with
+send_command. You should convert all uses of delay_factor and max_loops
+over to read_timeout=x where x is the total number of seconds to wait
+before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if expect_string is not None:
search_pattern = expect_string
+ else:
+ search_pattern = self._prompt_handler(auto_find_prompt)
if normalize:
command_string = self.normalize_cmd(command_string)
- time.sleep(delay_factor * loop_delay)
- self.clear_buffer()
+ # Start the clock
+ start_time = time.time()
self.write_channel(command_string)
new_data = ""
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
- # Strip off everything before the command echo (to avoid false positives on the prompt)
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- new_data = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
- i = 1
+ MAX_CHARS = 2_000_000
+ DEQUE_SIZE = 20
output = ""
- past_three_reads = deque(maxlen=3)
+ # Check only the past N-reads. This is for the case where the output is
+ # very large (i.e. searching a very large string for a pattern a whole bunch of times)
+ past_n_reads: Deque[str] = deque(maxlen=DEQUE_SIZE)
first_line_processed = False
- # Keep reading data until search_pattern is found or until max_loops is reached.
- while i <= max_loops:
+ # Keep reading data until search_pattern is found or until read_timeout
+ while time.time() - start_time < read_timeout:
if new_data:
output += new_data
- past_three_reads.append(new_data)
+ past_n_reads.append(new_data)
# Case where we haven't processed the first_line yet (there is a potential issue
# in the first line (in cases where the line is repainted).
@@ -3780,19 +4121,30 @@
Classes
break
else:
- # Check if pattern is in the past three reads
- if re.search(search_pattern, "".join(past_three_reads)):
- break
-
- time.sleep(delay_factor * loop_delay)
- i += 1
+ if len(output) <= MAX_CHARS:
+ if re.search(search_pattern, output):
+ break
+ else:
+ # Switch to deque mode if output is greater than MAX_CHARS
+ # Check if pattern is in the past n reads
+ if re.search(search_pattern, "".join(past_n_reads)):
+ break
+
+ time.sleep(loop_delay)
new_data = self.read_channel()
+
else: # nobreak
- raise IOError(
- "Search pattern never detected in send_command: {}".format(
- search_pattern
- )
- )
+ msg = f"""
+Pattern not detected: {repr(search_pattern)} in output.
+
+Things you might try to fix this:
+1. Explicitly set your pattern using the expect_string argument.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.
+
+"""
+ raise ReadTimeout(msg)
output = self._sanitize_output(
output,
@@ -3800,45 +4152,98 @@
Classes
command_string=command_string,
strip_prompt=strip_prompt,
)
+ return_val = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
+ )
+ return return_val
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
+ def _send_command_str(self, *args: Any, **kwargs: Any) -> str:
+ """Wrapper for `send_command` method that always returns a string"""
+ output = self.send_command(*args, **kwargs)
+ assert isinstance(output, str)
return output
- def send_command_expect(self, *args, **kwargs):
- """Support previous name of send_command method.
+ def send_command_expect(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """Support previous name of send_command method."""
+ return self.send_command(*args, **kwargs)
+
+ def _multiline_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
+ strip_prompt = kwargs.get("strip_prompt", False)
+ kwargs["strip_prompt"] = strip_prompt
+ strip_command = kwargs.get("strip_command", False)
+ kwargs["strip_command"] = strip_command
+ return kwargs
+
+ def send_multiline(
+ self,
+ commands: Sequence[Union[str, List[str]]],
+ multiline: bool = True,
+ **kwargs: Any,
+ ) -> str:
+ """
+ commands should either be:
+
+ commands = [[cmd1, expect1], [cmd2, expect2], ...]]
+
+ Or
- :param args: Positional arguments to send to send_command()
- :type args: list
+ commands = [cmd1, cmd2, cmd3, ...]
+
+ Any expect_string that is a null-string will use pattern based on
+ device's prompt (unless expect_string argument is passed in via
+ kwargs.
- :param kwargs: Keyword arguments to send to send_command()
- :type kwargs: dict
"""
- return self.send_command(*args, **kwargs)
+ output = ""
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+
+ default_expect_string = kwargs.pop("expect_string", None)
+ if not default_expect_string:
+ auto_find_prompt = kwargs.get("auto_find_prompt", True)
+ default_expect_string = self._prompt_handler(auto_find_prompt)
+
+ if commands and isinstance(commands[0], str):
+ # If list of commands just send directly using default_expect_string (probably prompt)
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_str(
+ cmd, expect_string=default_expect_string, **kwargs
+ )
+ else:
+ # If list of lists, then first element is cmd and second element is expect_string
+ for cmd_item in commands:
+ assert not isinstance(cmd_item, str)
+ cmd, expect_string = cmd_item
+ if not expect_string:
+ expect_string = default_expect_string
+ output += self._send_command_str(
+ cmd, expect_string=expect_string, **kwargs
+ )
+ return output
+
+ def send_multiline_timing(
+ self, commands: Sequence[str], multiline: bool = True, **kwargs: Any
+ ) -> str:
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+ output = ""
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_timing_str(cmd, **kwargs)
+ return output
@staticmethod
- def strip_backspaces(output):
+ def strip_backspaces(output: str) -> str:
"""Strip any backspace characters out of the output.
:param output: Output obtained from a remote network device.
@@ -3847,7 +4252,7 @@
# command_string isn't there; do nothing
return output
- def normalize_linefeeds(self, a_string):
+ def normalize_linefeeds(self, a_string: str) -> str:
"""Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
:param a_string: A string that may have non-normalized line feeds
@@ -3891,7 +4296,7 @@
Classes
else:
return a_string
- def normalize_cmd(self, command):
+ def normalize_cmd(self, command: str) -> str:
"""Normalize CLI commands to have a single trailing newline.
:param command: Command that may require line feed to be normalized
@@ -3901,32 +4306,32 @@
Classes
command += self.RETURN
return command
- def check_enable_mode(self, check_string=""):
+ def check_enable_mode(self, check_string: str = "") -> bool:
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
"""
self.write_channel(self.RETURN)
- output = self.read_until_prompt()
+ output = self.read_until_prompt(read_entire_line=True)
return check_string in output
def enable(
- self, cmd="", pattern="ssword", enable_pattern=None, re_flags=re.IGNORECASE
- ):
+ self,
+ cmd: str = "",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
"""Enter enable mode.
:param cmd: Device command to enter enable mode
- :type cmd: str
:param pattern: pattern to search for indicating device is waiting for password
- :type pattern: str
:param enable_pattern: pattern indicating you have entered enable mode
- :type pattern: str
:param re_flags: Regular expression flags used in conjunction with pattern
- :type re_flags: int
"""
output = ""
msg = (
@@ -3965,7 +4370,7 @@
Automatically exits/enters configuration mode.
:param config_commands: Multiple configuration commands to be sent to the device
- :type config_commands: list or string
:param exit_config_mode: Determines whether or not to exit config mode after complete
- :type exit_config_mode: bool
- :param delay_factor: Factor to adjust delays
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor (default: 150)
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Determines whether or not to strip the prompt
- :type strip_prompt: bool
:param strip_command: Determines whether or not to strip the command
- :type strip_command: bool
+
+ :param read_timeout: Absolute timer to send to read_channel_timing. Should be rarely needed.
:param config_mode_command: The command to enter into config mode
- :type config_mode_command: str
:param cmd_verify: Whether or not to verify command echo for each command in config_set
- :type cmd_verify: bool
:param enter_config_mode: Do you enter config mode before sending config commands
- :type exit_config_mode: bool
:param error_pattern: Regular expression pattern to detect config errors in the
output.
- :type error_pattern: str
+
+ :param terminator: Regular expression pattern to use as an alternate terminator in certain
+ situations.
+
+ :param bypass_commands: Regular expression pattern indicating configuration commands
+ where cmd_verify is automatically disabled.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if self.global_cmd_verify is not None:
+ cmd_verify = self.global_cmd_verify
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ # Calculate an equivalent read_timeout (if using old settings)
+ # Eliminate in Netmiko 5.x
+ if read_timeout is None:
+ max_loops = 150 if max_loops is None else max_loops
+ delay_factor = 1.0 if delay_factor is None else delay_factor
+
+ # If delay_factor has been set, then look at global_delay_factor
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ read_timeout = calc_old_timeout(
+ max_loops=max_loops, delay_factor=delay_factor, loop_delay=0.1
+ )
+
+ if delay_factor is None:
+ delay_factor = self.select_delay_factor(0)
+ else:
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ if read_timeout is None:
+ read_timeout = 15
+ else:
+ read_timeout = read_timeout
+
if config_commands is None:
return ""
elif isinstance(config_commands, str):
@@ -4125,20 +4568,33 @@
Classes
if not hasattr(config_commands, "__iter__"):
raise ValueError("Invalid argument passed into send_config_set")
+ if bypass_commands is None:
+ # Commands where cmd_verify is automatically disabled reg-ex logical-or
+ bypass_commands = r"^banner .*$"
+
+ # Set bypass_commands="" to force no-bypass (usually for testing)
+ bypass_detected = False
+ if bypass_commands:
+ bypass_detected = any(
+ [True for cmd in config_commands if re.search(bypass_commands, cmd)]
+ )
+ if bypass_detected:
+ cmd_verify = False
+
# Send config commands
output = ""
if enter_config_mode:
- cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
- output += self.config_mode(*cfg_mode_args)
+ if config_mode_command:
+ output += self.config_mode(config_mode_command)
+ else:
+ output += self.config_mode()
- # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ # Perform output gathering line-by-line (legacy way)
if self.fast_cli and self._legacy_mode and not error_pattern:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
elif not cmd_verify:
for cmd in config_commands:
@@ -4147,35 +4603,25 @@
Classes
# Gather the output incrementally due to error_pattern requirements
if error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
if re.search(error_pattern, output, flags=re.M):
msg = f"Invalid input detected at command: {cmd}"
raise ConfigInvalidException(msg)
# Standard output gathering (no error_pattern)
if not error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Make sure command is echoed
- new_output = self.read_until_pattern(pattern=re.escape(cmd.strip()))
- output += new_output
-
- # We might capture next prompt in the original read
- pattern = f"(?:{re.escape(self.base_prompt)}|#)"
- if not re.search(pattern, new_output):
- # Make sure trailing prompt comes back (after command)
- # NX-OS has fast-buffering problem where it immediately echoes command
- # Even though the device hasn't caught up with processing command.
- new_output = self.read_until_pattern(pattern=pattern)
- output += new_output
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+
+ # Read until next prompt or terminator (#); the .*$ forces read of entire line
+ pattern = f"(?:{re.escape(self.base_prompt)}.*$|{terminator}.*$)"
+ output += self.read_until_pattern(pattern=pattern, re_flags=re.M)
if error_pattern:
if re.search(error_pattern, output, flags=re.M):
@@ -4188,7 +4634,7 @@
Classes
log.debug(f"{output}")
return output
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Remove any ANSI (VT100) ESC codes from the output
@@ -4209,10 +4655,11 @@
Classes
ESC[?6l Reset mode screen with options 640 x 200 monochrome (graphics)
ESC[?7l Disable line wrapping
ESC[2J Code erase display
- ESC[00;32m Color Green (30 to 37 are different colors) more general pattern is
- ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+ ESC[00;32m Color Green (30 to 37 are different colors)
ESC[6n Get cursor position
ESC[1D Move cursor position leftward by x characters (1 in this case)
+ ESC[9999B Move cursor down N-lines (very large value is attempt to move to the
+ very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
@@ -4234,7 +4681,8 @@
return output
- def cleanup(self, command=""):
+ def cleanup(self, command: str = "") -> None:
"""Logout of the session on the network device plus any additional cleanup."""
pass
- def paramiko_cleanup(self):
+ def paramiko_cleanup(self) -> None:
"""Cleanup Paramiko to try to gracefully handle SSH session ending."""
- self.remote_conn_pre.close()
+ if self.remote_conn_pre is not None:
+ self.remote_conn_pre.close()
del self.remote_conn_pre
- def disconnect(self):
+ def disconnect(self) -> None:
"""Try to gracefully close the session."""
try:
self.cleanup()
if self.protocol == "ssh":
self.paramiko_cleanup()
elif self.protocol == "telnet":
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
self.remote_conn.close()
elif self.protocol == "serial":
+ assert isinstance(self.remote_conn, serial.Serial)
self.remote_conn.close()
except Exception:
# There have been race conditions observed on disconnect.
@@ -4310,31 +4772,25 @@
Classes
finally:
self.remote_conn_pre = None
self.remote_conn = None
- self.close_session_log()
+ if self.session_log:
+ self.session_log.close()
- def commit(self):
+ def commit(self) -> str:
"""Commit method for platforms that support this."""
raise AttributeError("Network device does not support 'commit()' method")
- def save_config(self, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
- def open_session_log(self, filename, mode="write"):
- """Open the session_log file."""
- if mode == "append":
- self.session_log = open(filename, mode="a", encoding=self.encoding)
- else:
- self.session_log = open(filename, mode="w", encoding=self.encoding)
- self._session_log_close = True
-
- def close_session_log(self):
- """Close the session_log file (if it is a file that we opened)."""
- if self.session_log is not None and self._session_log_close:
- self.session_log.close()
- self.session_log = None
-
- def run_ttp(self, template, res_kwargs={}, **kwargs):
+ def run_ttp(
+ self,
+ template: Union[str, bytes, "PathLike[Any]"],
+ res_kwargs: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Any:
"""
Run TTP template parsing by using input parameters to collect
devices output.
@@ -4342,29 +4798,25 @@
Classes
:param template: template content, OS path to template or reference
to template within TTP templates collection in
ttp://path/to/template.txt format
- :type template: str
:param res_kwargs: ``**res_kwargs`` arguments to pass to TTP result method
- :type res_kwargs: dict
:param kwargs: any other ``**kwargs`` to use for TTP object instantiation
- :type kwargs: dict
TTP template must have inputs defined together with below parameters.
:param method: name of Netmiko connection object method to call, default ``send_command``
- :type method: str
:param kwargs: Netmiko connection object method arguments
- :type kwargs: dict
:param commands: list of commands to collect
- :type commands: list
Inputs' load could be of one of the supported formats and controlled by input's ``load``
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
"""
+ if res_kwargs is None:
+ res_kwargs = {}
return run_ttp_template(
connection=self, template=template, res_kwargs=res_kwargs, **kwargs
)
@@ -4404,7 +4856,7 @@
Static methods
Source code
@staticmethod
-def strip_backspaces(output):
+def strip_backspaces(output: str) -> str:
"""Strip any backspace characters out of the output.
:param output: Output obtained from a remote network device.
@@ -4428,7 +4880,7 @@
def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not.
:param check_string: Identification of configuration mode from the device
@@ -4440,7 +4892,7 @@
Methods
self.write_channel(self.RETURN)
# You can encounter an issue here (on router name changes) prefer delay-based solution
if not pattern:
- output = self._read_channel_timing()
+ output = self.read_channel_timing()
else:
output = self.read_until_pattern(pattern=pattern)
return check_string in output
@@ -4455,14 +4907,14 @@
Methods
:type check_string: str
Source code
-
def check_enable_mode(self, check_string=""):
+
def check_enable_mode(self, check_string: str = "") -> bool:
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
"""
self.write_channel(self.RETURN)
- output = self.read_until_prompt()
+ output = self.read_until_prompt(read_entire_line=True)
return check_string in output
@@ -4473,45 +4925,70 @@
Methods
Logout of the session on the network device plus any additional cleanup.
Source code
-
def cleanup(self, command=""):
+
def cleanup(self, command: str = "") -> None:
"""Logout of the session on the network device plus any additional cleanup."""
pass
def clear_buffer(
+ self,
+ backoff: bool = True,
+ backoff_max: float = 3.0,
+ delay_factor: Optional[float] = None,
+) -> str:
"""Read any data available in the channel."""
- sleep_time = 0.1 * self.global_delay_factor
+
+ if delay_factor is None:
+ delay_factor = self.global_delay_factor
+ sleep_time = 0.1 * delay_factor
+
+ output = ""
for _ in range(10):
time.sleep(sleep_time)
data = self.read_channel()
+ data = self.strip_ansi_escape_codes(data)
+ output += data
if not data:
break
# Double sleep time each time we detect data
log.debug("Clear buffer detects data in the channel")
if backoff:
sleep_time *= 2
- sleep_time = 3 if sleep_time >= 3 else sleep_time
Close the session_log file (if it is a file that we opened).
+
Source code
-
def close_session_log(self):
- """Close the session_log file (if it is a file that we opened)."""
- if self.session_log is not None and self._session_log_close:
- self.session_log.close()
- self.session_log = None
+
def command_echo_read(self, cmd: str, read_timeout: float) -> str:
+
+ # Make sure you read until you detect the command echo (avoid getting out of sync)
+ new_data = self.read_until_pattern(
+ pattern=re.escape(cmd), read_timeout=read_timeout
+ )
+
+ # There can be echoed prompts that haven't been cleared before the cmd echo
+ # this can later mess up the trailing prompt pattern detection. Clear this out.
+ lines = new_data.split(cmd)
+ if len(lines) == 2:
+ # lines[-1] should realistically just be the null string
+ new_data = f"{cmd}{lines[-1]}"
+ else:
+ # cmd exists in the output multiple times? Just retain the original output
+ pass
+ return new_data
@@ -4521,7 +4998,7 @@
Methods
Commit method for platforms that support this.
Source code
-
def commit(self):
+
def commit(self) -> str:
"""Commit method for platforms that support this."""
raise AttributeError("Network device does not support 'commit()' method")
def config_mode(
+ self, config_command: str = "", pattern: str = "", re_flags: int = 0
+) -> str:
"""Enter into config_mode.
:param config_command: Configuration command to send to the device
@@ -4559,45 +5038,51 @@
Methods
output += self.read_until_pattern(
pattern=re.escape(config_command.strip())
)
- if not re.search(pattern, output, flags=re_flags):
+ if pattern:
output += self.read_until_pattern(pattern=pattern, re_flags=re_flags)
+ else:
+ output += self.read_until_prompt(read_entire_line=True)
if not self.check_config_mode():
raise ValueError("Failed to enter configuration mode.")
return output
def establish_connection(self, width: int = 511, height: int = 1000) -> None:
"""Establish SSH connection to the network device
Timeout will generate a NetmikoTimeoutException
@@ -4726,16 +5210,21 @@
Finds the current network device prompt, last line only.
:param delay_factor: See init: global_delay_factor
-:type delay_factor: int
+:type delay_factor: int
+
:param pattern: Regular expression pattern to determine whether prompt is valid
Source code
-
def find_prompt(self, delay_factor=1):
+
def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+) -> str:
"""Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
+
+ :param pattern: Regular expression pattern to determine whether prompt is valid
"""
delay_factor = self.select_delay_factor(delay_factor)
+ sleep_time = delay_factor * 0.25
self.clear_buffer()
self.write_channel(self.RETURN)
- sleep_time = delay_factor * 0.1
- time.sleep(sleep_time)
- # Initial attempt to get prompt
- prompt = self.read_channel().strip()
-
- # Check if the only thing you received was a newline
- count = 0
- while count <= 12 and not prompt:
+ if pattern:
+ try:
+ prompt = self.read_until_pattern(pattern=pattern)
+ except ReadTimeout:
+ pass
+ else:
+ # Initial read
+ time.sleep(sleep_time)
prompt = self.read_channel().strip()
- if not prompt:
- self.write_channel(self.RETURN)
- time.sleep(sleep_time)
- if sleep_time <= 3:
- # Double the sleep_time when it is small
- sleep_time *= 2
- else:
- sleep_time += 1
- count += 1
+
+ count = 0
+ while count <= 12 and not prompt:
+ if not prompt:
+ self.write_channel(self.RETURN)
+ time.sleep(sleep_time)
+ prompt = self.read_channel().strip()
+ if sleep_time <= 3:
+ # Double the sleep_time when it is small
+ sleep_time *= 2
+ else:
+ sleep_time += 1
+ count += 1
# If multiple lines in the output take the last line
- prompt = self.normalize_linefeeds(prompt)
prompt = prompt.split(self.RESPONSE_RETURN)[-1]
prompt = prompt.strip()
+ self.clear_buffer()
if not prompt:
raise ValueError(f"Unable to find prompt: {prompt}")
- time.sleep(delay_factor * 0.1)
- self.clear_buffer()
log.debug(f"[find_prompt()]: prompt is {prompt}")
return prompt
@@ -4923,7 +5434,7 @@
Methods
Returns a boolean flag with the state of the connection.
Source code
-
def is_alive(self):
+
def is_alive(self) -> bool:
"""Returns a boolean flag with the state of the connection."""
null = chr(0)
if self.remote_conn is None:
@@ -4935,9 +5446,11 @@
Methods
# IAC = Interpret as Command; it comes before the NOP.
log.debug("Sending IAC + NOP")
# Need to send multiple times to test connection
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
+ telnet_socket = self.remote_conn.get_socket()
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
return True
except AttributeError:
return False
@@ -4947,7 +5460,11 @@
Methods
# Try sending ASCII null byte to maintain the connection alive
log.debug("Sending the NULL byte")
self.write_channel(null)
- return self.remote_conn.transport.is_active()
+ assert isinstance(self.remote_conn, paramiko.Channel)
+ assert self.remote_conn.transport is not None
+ result = self.remote_conn.transport.is_active()
+ assert isinstance(result, bool)
+ return result
except (socket.error, EOFError):
log.error("Unable to send", exc_info=True)
# If unable to send, we can tell for sure that the connection is unusable
@@ -4964,7 +5481,7 @@
Methods
:type command: str
Source code
-
def normalize_cmd(self, command):
+
def normalize_cmd(self, command: str) -> str:
"""Normalize CLI commands to have a single trailing newline.
:param command: Command that may require line feed to be normalized
@@ -4990,7 +5507,7 @@
Methods
Source code
-
def normalize_linefeeds(self, a_string):
+
def normalize_linefeeds(self, a_string: str) -> str:
"""Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
:param a_string: A string that may have non-normalized line feeds
@@ -5006,22 +5523,6 @@
Cleanup Paramiko to try to gracefully handle SSH session ending.
Source code
-
def paramiko_cleanup(self):
+
def paramiko_cleanup(self) -> None:
"""Cleanup Paramiko to try to gracefully handle SSH session ending."""
- self.remote_conn_pre.close()
+ if self.remote_conn_pre is not None:
+ self.remote_conn_pre.close()
del self.remote_conn_pre
@@ -5039,105 +5541,295 @@
Methods
def read_channel(self)
-
Generic handler that will read all the data from an SSH or telnet channel.
+
Generic handler that will read all the data from given channel.
Source code
-
def read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- output = ""
- self._lock_netmiko_session()
- try:
- output = self._read_channel()
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+
@lock_channel
+def read_channel(self) -> str:
+ """Generic handler that will read all the data from given channel."""
+ new_data = self.channel.read_channel()
+ new_data = self.normalize_linefeeds(new_data)
+ if self.ansi_escape_codes:
+ new_data = self.strip_ansi_escape_codes(new_data)
+ log.debug(f"read_channel: {new_data}")
+ if self.session_log:
+ self.session_log.write(new_data)
+
+ # If data had been previously saved to the buffer, the prepend it to output
+ # do post read_channel so session_log/log doesn't record buffered data twice
+ if self._read_buffer:
+ output = self._read_buffer + new_data
+ self._read_buffer = ""
+ else:
+ output = new_data
return output
Read channel until pattern detected. Return ALL data available.
+
Read data on the channel based on timing delays.
+
General pattern is keep reading until no new data is read.
+Once no new data is read wait last_read amount of time (one last read).
+As long as no new data, then return data.
+
read_timeout is an absolute timer for how long to keep reading (which presupposes
+we are still getting new data).
+
Setting read_timeout to zero will cause read_channel_timing to never expire based
+on an absolute timeout. It will only complete based on timeout based on their being
+no new data.
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
Source code
-
def read_until_pattern(self, *args, **kwargs):
- """Read channel until pattern detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
-
-
+
def read_channel_timing(
+ self,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read data on the channel based on timing delays.
+
+ General pattern is keep reading until no new data is read.
+ Once no new data is read wait `last_read` amount of time (one last read).
+ As long as no new data, then return data.
+
+ `read_timeout` is an absolute timer for how long to keep reading (which presupposes
+ we are still getting new data).
+
+ Setting `read_timeout` to zero will cause read_channel_timing to never expire based
+ on an absolute timeout. It will only complete based on timeout based on their being
+ no new data.
+
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ # Time to delay in each read loop
+ loop_delay = 0.1
+ channel_data = ""
+ start_time = time.time()
+
+ # Set read_timeout to 0 to never timeout
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ time.sleep(loop_delay)
+ new_data = self.read_channel()
+ # gather new output
+ if new_data:
+ channel_data += new_data
+ # if we have some output, but nothing new, then do the last read
+ elif channel_data != "":
+ # Make sure really done (i.e. no new data)
+ time.sleep(last_read)
+ new_data = self.read_channel()
+ if not new_data:
+ break
+ else:
+ channel_data += new_data
+ else:
+ msg = f"""\n
+read_channel_timing's absolute timer expired.
+
+The network device was continually outputting data for longer than {read_timeout}
+seconds.
+
+If this is expected i.e. the command you are executing is continually emitting
+data for a long period of time, then you can set 'read_timeout=x' seconds. If
+you want Netmiko to keep reading indefinitely (i.e. to only stop when there is
+no new data), then you can set 'read_timeout=0'.
+
+You can look at the Netmiko session_log or debug log for more information.
+
+"""
+ raise ReadTimeout(msg)
+ return channel_data
Returns ReadTimeout if pattern not detected in read_timeout seconds.
+
:param pattern: Regular expression pattern used to identify that reading is done.
+
:param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+reading indefinitely until pattern is detected.
+
:param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
+Source code
+
def read_until_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel until pattern is detected.
+
+ Will return string up to and including pattern.
+
+ Returns ReadTimeout if pattern not detected in read_timeout seconds.
+
+ :param pattern: Regular expression pattern used to identify that reading is done.
+
+ :param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+ A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+ reading indefinitely until pattern is detected.
+
+ :param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
+
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of max_loops with read_until_pattern.
+You should convert all uses of max_loops over to read_timeout=x
+where x is the total number of seconds to wait before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ output = ""
+ loop_delay = 0.01
+ start_time = time.time()
+ # if read_timeout == 0 or 0.0 keep reading indefinitely
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ output += self.read_channel()
+ if re.search(pattern, output, flags=re_flags):
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ # The string matched by pattern must be retained in the output string.
+ # re.split will do this if capturing parentesis are used.
+ if len(results) == 2:
+ # no capturing parenthesis, convert and try again.
+ pattern = f"({pattern})"
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ if len(results) != 3:
+ # well, we tried
+ msg = f"""Unable to successfully split output based on pattern:
+pattern={pattern}
+output={repr(output)}
+results={results}
+"""
+ raise ReadException(msg)
+
+ # Process such that everything before and including pattern is return.
+ # Everything else is retained in the _read_buffer
+ output, match_str, buffer = results
+ output = output + match_str
+ if buffer:
+ self._read_buffer += buffer
+ log.debug(f"Pattern found: {pattern} {output}")
+ return output
+ time.sleep(loop_delay)
+
+ msg = f"""\n\nPattern not detected: {repr(pattern)} in output.
+
+Things you might try to fix this:
+1. Adjust the regex pattern to better identify the terminating string. Note, in
+many situations the pattern is automatically based on the network device's prompt.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.\n\n"""
+ raise ReadTimeout(msg)
Read until either self.base_prompt or pattern is detected.
-
:param pattern: the pattern used to identify that the output is complete (i.e. stop
-reading when pattern is detected). pattern will be combined with self.base_prompt to
-terminate output reading when the first of self.base_prompt or pattern is detected.
-:type pattern: regular expression string
-
:param re_flags: regex flags used in conjunction with pattern to search for prompt
-(defaults to no flags)
-:type re_flags: int
+
Read until either self.base_prompt or pattern is detected.
Source code
-
def read_until_prompt_or_pattern(self, pattern="", re_flags=0):
- """Read until either self.base_prompt or pattern is detected.
-
- :param pattern: the pattern used to identify that the output is complete (i.e. stop \
- reading when pattern is detected). pattern will be combined with self.base_prompt to \
- terminate output reading when the first of self.base_prompt or pattern is detected.
- :type pattern: regular expression string
-
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
-
- """
- combined_pattern = re.escape(self.base_prompt)
+
def read_until_prompt_or_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+) -> str:
+ """Read until either self.base_prompt or pattern is detected."""
+ prompt_pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ prompt_pattern = f"{prompt_pattern}.*"
if pattern:
- combined_pattern = r"({}|{})".format(combined_pattern, pattern)
- return self._read_channel_expect(combined_pattern, re_flags=re_flags)
Run TTP template parsing by using input parameters to collect
devices output.
:param template: template content, OS path to template or reference
to template within TTP templates collection in
-ttp://path/to/template.txt format
-:type template: str
-
:param res_kwargs: **res_kwargs arguments to pass to TTP result method
-:type res_kwargs: dict
-
:param kwargs: any other **kwargs to use for TTP object instantiation
-:type kwargs: dict
+ttp://path/to/template.txt format
+
:param res_kwargs: **res_kwargs arguments to pass to TTP result method
+
:param kwargs: any other **kwargs to use for TTP object instantiation
TTP template must have inputs defined together with below parameters.
-
:param method: name of Netmiko connection object method to call, default send_command
-:type method: str
Inputs' load could be of one of the supported formats and controlled by input's load
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
def run_ttp(
+ self,
+ template: Union[str, bytes, "PathLike[Any]"],
+ res_kwargs: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+) -> Any:
"""
Run TTP template parsing by using input parameters to collect
devices output.
@@ -5145,42 +5837,40 @@
Methods
:param template: template content, OS path to template or reference
to template within TTP templates collection in
ttp://path/to/template.txt format
- :type template: str
:param res_kwargs: ``**res_kwargs`` arguments to pass to TTP result method
- :type res_kwargs: dict
:param kwargs: any other ``**kwargs`` to use for TTP object instantiation
- :type kwargs: dict
TTP template must have inputs defined together with below parameters.
:param method: name of Netmiko connection object method to call, default ``send_command``
- :type method: str
:param kwargs: Netmiko connection object method arguments
- :type kwargs: dict
:param commands: list of commands to collect
- :type commands: list
Inputs' load could be of one of the supported formats and controlled by input's ``load``
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
"""
+ if res_kwargs is None:
+ res_kwargs = {}
return run_ttp_template(
connection=self, template=template, res_kwargs=res_kwargs, **kwargs
)
def select_delay_factor(self, delay_factor: float) -> float:
"""
Choose the greater of delay_factor or self.global_delay_factor (default).
In fast_cli choose the lesser of delay_factor of self.global_delay_factor.
@@ -5216,429 +5906,356 @@
Execute command_string on the SSH channel using a pattern-based mechanism. Generally
used for show commands. By default this method will keep waiting to receive data until the
network device prompt is detected. The current network device prompt will be determined
automatically.
-
:param command_string: The command to be executed on the remote device.
-:type command_string: str
+
:param command_string: The command to be executed on the remote device.
:param expect_string: Regular expression pattern to use for determining end of output.
-If left blank will default to being based on router prompt.
-:type expect_string: str
-
:param delay_factor: Multiplying factor used to adjust delays (default: 1).
-:type delay_factor: int
-
:param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
-based upon self.timeout.
-:type max_loops: int
-
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
-:type strip_prompt: bool
-
:param strip_command: Remove the echo of the command from the output (default: True).
-:type strip_command: bool
-
:param normalize: Ensure the proper enter is sent at end of command (default: True).
-:type normalize: bool
-
:param use_textfsm: Process command output through TextFSM template (default: False).
-:type normalize: bool
+If left blank will default to being based on router prompt.
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
+
:param strip_command: Remove the echo of the command from the output (default: True).
+
:param normalize: Ensure the proper enter is sent at end of command (default: True).
+
:param use_textfsm: Process command output through TextFSM template (default: False).
: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 use_ttp: Process command output through TTP template (default: False).
: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
+path, relative path, or name of file in current directory. (default: None).
+
:param use_genie: Process command output through PyATS/Genie parser (default: False).
+
:param cmd_verify: Verify command echo before proceeding (default: True).
Source code
-
@select_cmd_verify
-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
- used for show commands. By default this method will keep waiting to receive data until the
- network device prompt is detected. The current network device prompt will be determined
- automatically.
+
@select_cmd_verify
+ def send_command(
+ self,
+ command_string: str,
+ expect_string: Optional[str] = None,
+ read_timeout: float = 10.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ auto_find_prompt: bool = True,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = True,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """Execute command_string on the SSH channel using a pattern-based mechanism. Generally
+ used for show commands. By default this method will keep waiting to receive data until the
+ network device prompt is detected. The current network device prompt will be determined
+ automatically.
- :param command_string: The command to be executed on the remote device.
- :type command_string: str
+ :param command_string: The command to be executed on the remote device.
+
+ :param expect_string: Regular expression pattern to use for determining end of output.
+ If left blank will default to being based on router prompt.
- :param expect_string: Regular expression pattern to use for determining end of output.
- If left blank will default to being based on router prompt.
- :type expect_string: str
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
+ :param strip_command: Remove the echo of the command from the output (default: True).
- :param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
+ :param normalize: Ensure the proper enter is sent at end of command (default: True).
- :param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
+ :param use_textfsm: Process command output through TextFSM template (default: False).
- :param use_textfsm: Process command output through TextFSM template (default: False).
- :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 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).
- :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).
- :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).
- :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).
+ """
- :param cmd_verify: Verify command echo before proceeding (default: True).
- :type cmd_verify: bool
- """
+ # Time to delay in each read loop
+ loop_delay = 0.025
- # Time to delay in each read loop
- loop_delay = 0.2
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 500:
- # Default arguments are being used; use self.timeout instead
- max_loops = int(self.timeout / loop_delay)
+ if self.delay_factor_compat:
+ # For compatibility calculate the old equivalent read_timeout
+ # i.e. what it would have been in Netmiko 3.x
+ if delay_factor is None:
+ tmp_delay_factor = self.global_delay_factor
+ else:
+ tmp_delay_factor = self.select_delay_factor(delay_factor)
+ compat_timeout = calc_old_timeout(
+ max_loops=max_loops,
+ delay_factor=tmp_delay_factor,
+ loop_delay=0.2,
+ old_timeout=self.timeout,
+ )
+ msg = f"""\n
+You have chosen to use Netmiko's delay_factor compatibility mode for
+send_command. This will revert Netmiko to behave similarly to how it
+did in Netmiko 3.x (i.e. to use delay_factor/global_delay_factor and
+max_loops).
+
+Using these parameters Netmiko has calculated an effective read_timeout
+of {compat_timeout} and will set the read_timeout to this value.
+
+Please convert your code to that new format i.e.:
+
+ net_connect.send_command(cmd, read_timeout={compat_timeout})
+
+And then disable delay_factor_compat.
+
+delay_factor_compat will be removed in Netmiko 5.x.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ # Override the read_timeout with Netmiko 3.x way :-(
+ read_timeout = compat_timeout
- # Find the current router prompt
- if expect_string is None:
- if auto_find_prompt:
- try:
- prompt = self.find_prompt(delay_factor=delay_factor)
- except ValueError:
- prompt = self.base_prompt
else:
- prompt = self.base_prompt
- search_pattern = re.escape(prompt.strip())
- else:
- search_pattern = expect_string
+ # No need for two deprecation messages so only display this if not using
+ # delay_factor_compat
+ if delay_factor is not None or max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of delay_factor/max_loops with
+send_command. You should convert all uses of delay_factor and max_loops
+over to read_timeout=x where x is the total number of seconds to wait
+before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if expect_string is not None:
+ search_pattern = expect_string
+ else:
+ search_pattern = self._prompt_handler(auto_find_prompt)
- if normalize:
- command_string = self.normalize_cmd(command_string)
+ if normalize:
+ command_string = self.normalize_cmd(command_string)
- time.sleep(delay_factor * loop_delay)
- self.clear_buffer()
- self.write_channel(command_string)
- new_data = ""
+ # Start the clock
+ start_time = time.time()
+ self.write_channel(command_string)
+ new_data = ""
- cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
- if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
- # Strip off everything before the command echo (to avoid false positives on the prompt)
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- new_data = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
+ cmd = command_string.strip()
+ if cmd and cmd_verify:
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
- i = 1
- output = ""
- past_three_reads = deque(maxlen=3)
- first_line_processed = False
+ MAX_CHARS = 2_000_000
+ DEQUE_SIZE = 20
+ output = ""
+ # Check only the past N-reads. This is for the case where the output is
+ # very large (i.e. searching a very large string for a pattern a whole bunch of times)
+ past_n_reads: Deque[str] = deque(maxlen=DEQUE_SIZE)
+ first_line_processed = False
- # Keep reading data until search_pattern is found or until max_loops is reached.
- while i <= max_loops:
- if new_data:
- output += new_data
- past_three_reads.append(new_data)
-
- # Case where we haven't processed the first_line yet (there is a potential issue
- # in the first line (in cases where the line is repainted).
- if not first_line_processed:
- output, first_line_processed = self._first_line_handler(
- output, search_pattern
- )
- # Check if we have already found our pattern
- if re.search(search_pattern, output):
- break
+ # Keep reading data until search_pattern is found or until read_timeout
+ while time.time() - start_time < read_timeout:
+ if new_data:
+ output += new_data
+ past_n_reads.append(new_data)
- else:
- # Check if pattern is in the past three reads
- if re.search(search_pattern, "".join(past_three_reads)):
- break
+ # Case where we haven't processed the first_line yet (there is a potential issue
+ # in the first line (in cases where the line is repainted).
+ if not first_line_processed:
+ output, first_line_processed = self._first_line_handler(
+ output, search_pattern
+ )
+ # Check if we have already found our pattern
+ if re.search(search_pattern, output):
+ break
- time.sleep(delay_factor * loop_delay)
- i += 1
- new_data = self.read_channel()
- else: # nobreak
- raise IOError(
- "Search pattern never detected in send_command: {}".format(
- search_pattern
- )
- )
+ else:
+ if len(output) <= MAX_CHARS:
+ if re.search(search_pattern, output):
+ break
+ else:
+ # Switch to deque mode if output is greater than MAX_CHARS
+ # Check if pattern is in the past n reads
+ if re.search(search_pattern, "".join(past_n_reads)):
+ break
+
+ time.sleep(loop_delay)
+ new_data = self.read_channel()
- output = self._sanitize_output(
- output,
- strip_command=strip_command,
- command_string=command_string,
- strip_prompt=strip_prompt,
- )
+ else: # nobreak
+ msg = f"""
+Pattern not detected: {repr(search_pattern)} in output.
+
+Things you might try to fix this:
+1. Explicitly set your pattern using the expect_string argument.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
+"""
+ raise ReadTimeout(msg)
+
+ output = self._sanitize_output(
output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
+ strip_command=strip_command,
+ command_string=command_string,
+ strip_prompt=strip_prompt,
)
- # 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()
+ return_val = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
)
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
- return output
+ return return_val
def send_command_expect(self, *args, **kwargs)
-
Support previous name of send_command method.
-
:param args: Positional arguments to send to send_command()
-:type args: list
-
:param kwargs: Keyword arguments to send to send_command()
-:type kwargs: dict
+
Support previous name of send_command method.
Source code
-
def send_command_expect(self, *args, **kwargs):
- """Support previous name of send_command method.
-
- :param args: Positional arguments to send to send_command()
- :type args: list
-
- :param kwargs: Keyword arguments to send to send_command()
- :type kwargs: dict
- """
+
def send_command_expect(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
+ """Support previous name of send_command method."""
return self.send_command(*args, **kwargs)
Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
-
:param command_string: The command to be executed on the remote device.
-:type command_string: str
-
:param delay_factor: Multiplying factor used to adjust delays (default: 1).
-:type delay_factor: int or float
-
:param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
-based upon self.timeout.
-:type max_loops: int
-
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
-:type strip_prompt: bool
-
:param strip_command: Remove the echo of the command from the output (default: True).
-:type strip_command: bool
-
:param normalize: Ensure the proper enter is sent at end of command (default: True).
-:type normalize: bool
-
:param use_textfsm: Process command output through TextFSM template (default: False).
-:type use_textfsm: bool
+
:param command_string: The command to be executed on the remote device.
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
+
:param strip_command: Remove the echo of the command from the output (default: True).
+
:param normalize: Ensure the proper enter is sent at end of command (default: True).
+
:param use_textfsm: Process command output through TextFSM template (default: False).
: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
+path, relative path, or name of file in current directory. (default: None).
+
:param use_ttp: Process command output through TTP template (default: False).
: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
+path, relative path, or name of file in current directory. (default: None).
+
:param use_genie: Process command output through PyATS/Genie parser (default: False).
+
:param cmd_verify: Verify command echo before proceeding (default: False).
Source code
@select_cmd_verify
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,
-):
+ command_string: str,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = False,
+) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type use_textfsm: 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).
- :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).
- :type cmd_verify: bool
-
- :param cmd_echo: Deprecated (use cmd_verify instead)
- :type cmd_echo: bool
"""
-
- # For compatibility; remove cmd_echo in Netmiko 4.x.x
- if cmd_echo is not None:
- cmd_verify = cmd_echo
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
output = ""
- delay_factor = self.select_delay_factor(delay_factor)
-
+ new_data = ""
if normalize:
command_string = self.normalize_cmd(command_string)
self.write_channel(command_string)
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
-
- # Strip off everything before the command echo
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- output = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
- else:
- # cmd is in the actual output (not just echoed)
- output = new_data
-
- log.debug(f"send_command_timing current output: {output}")
-
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
+ output += new_data
+ output += self.read_channel_timing(
+ last_read=last_read, read_timeout=read_timeout
)
+
output = self._sanitize_output(
output,
strip_command=strip_command,
command_string=command_string,
strip_prompt=strip_prompt,
)
-
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
-
- log.debug(f"send_command_timing final output: {output}")
- return output
def send_config_from_file(
+ self, config_file: Union[str, bytes, "PathLike[Any]"], **kwargs: Any
+) -> str:
"""
Send configuration commands down the SSH channel from a file.
@@ -5648,59 +6265,57 @@
Methods
**kwargs are passed to send_config_set method.
:param config_file: Path to configuration file to be sent to the device
- :type config_file: str
:param kwargs: params to be sent to send_config_set method
- :type kwargs: dict
"""
with io.open(config_file, "rt", encoding="utf-8") as cfg_file:
- return self.send_config_set(cfg_file, **kwargs)
Automatically exits/enters configuration mode.
:param config_commands: Multiple configuration commands to be sent to the device
- :type config_commands: list or string
:param exit_config_mode: Determines whether or not to exit config mode after complete
- :type exit_config_mode: bool
- :param delay_factor: Factor to adjust delays
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor (default: 150)
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Determines whether or not to strip the prompt
- :type strip_prompt: bool
:param strip_command: Determines whether or not to strip the command
- :type strip_command: bool
+
+ :param read_timeout: Absolute timer to send to read_channel_timing. Should be rarely needed.
:param config_mode_command: The command to enter into config mode
- :type config_mode_command: str
:param cmd_verify: Whether or not to verify command echo for each command in config_set
- :type cmd_verify: bool
:param enter_config_mode: Do you enter config mode before sending config commands
- :type exit_config_mode: bool
:param error_pattern: Regular expression pattern to detect config errors in the
output.
- :type error_pattern: str
+
+ :param terminator: Regular expression pattern to use as an alternate terminator in certain
+ situations.
+
+ :param bypass_commands: Regular expression pattern indicating configuration commands
+ where cmd_verify is automatically disabled.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if self.global_cmd_verify is not None:
+ cmd_verify = self.global_cmd_verify
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ # Calculate an equivalent read_timeout (if using old settings)
+ # Eliminate in Netmiko 5.x
+ if read_timeout is None:
+ max_loops = 150 if max_loops is None else max_loops
+ delay_factor = 1.0 if delay_factor is None else delay_factor
+
+ # If delay_factor has been set, then look at global_delay_factor
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ read_timeout = calc_old_timeout(
+ max_loops=max_loops, delay_factor=delay_factor, loop_delay=0.1
+ )
+
+ if delay_factor is None:
+ delay_factor = self.select_delay_factor(0)
+ else:
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ if read_timeout is None:
+ read_timeout = 15
+ else:
+ read_timeout = read_timeout
+
if config_commands is None:
return ""
elif isinstance(config_commands, str):
@@ -5749,20 +6391,33 @@
Methods
if not hasattr(config_commands, "__iter__"):
raise ValueError("Invalid argument passed into send_config_set")
+ if bypass_commands is None:
+ # Commands where cmd_verify is automatically disabled reg-ex logical-or
+ bypass_commands = r"^banner .*$"
+
+ # Set bypass_commands="" to force no-bypass (usually for testing)
+ bypass_detected = False
+ if bypass_commands:
+ bypass_detected = any(
+ [True for cmd in config_commands if re.search(bypass_commands, cmd)]
+ )
+ if bypass_detected:
+ cmd_verify = False
+
# Send config commands
output = ""
if enter_config_mode:
- cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
- output += self.config_mode(*cfg_mode_args)
+ if config_mode_command:
+ output += self.config_mode(config_mode_command)
+ else:
+ output += self.config_mode()
- # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ # Perform output gathering line-by-line (legacy way)
if self.fast_cli and self._legacy_mode and not error_pattern:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
elif not cmd_verify:
for cmd in config_commands:
@@ -5771,35 +6426,25 @@
Methods
# Gather the output incrementally due to error_pattern requirements
if error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
if re.search(error_pattern, output, flags=re.M):
msg = f"Invalid input detected at command: {cmd}"
raise ConfigInvalidException(msg)
# Standard output gathering (no error_pattern)
if not error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Make sure command is echoed
- new_output = self.read_until_pattern(pattern=re.escape(cmd.strip()))
- output += new_output
-
- # We might capture next prompt in the original read
- pattern = f"(?:{re.escape(self.base_prompt)}|#)"
- if not re.search(pattern, new_output):
- # Make sure trailing prompt comes back (after command)
- # NX-OS has fast-buffering problem where it immediately echoes command
- # Even though the device hasn't caught up with processing command.
- new_output = self.read_until_pattern(pattern=pattern)
- output += new_output
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+
+ # Read until next prompt or terminator (#); the .*$ forces read of entire line
+ pattern = f"(?:{re.escape(self.base_prompt)}.*$|{terminator}.*$)"
+ output += self.read_until_pattern(pattern=pattern, re_flags=re.M)
if error_pattern:
if re.search(error_pattern, output, flags=re.M):
@@ -5813,8 +6458,89 @@
Any expect_string that is a null-string will use pattern based on
+device's prompt (unless expect_string argument is passed in via
+kwargs.
+
+Source code
+
def send_multiline(
+ self,
+ commands: Sequence[Union[str, List[str]]],
+ multiline: bool = True,
+ **kwargs: Any,
+) -> str:
+ """
+ commands should either be:
+
+ commands = [[cmd1, expect1], [cmd2, expect2], ...]]
+
+ Or
+
+ commands = [cmd1, cmd2, cmd3, ...]
+
+ Any expect_string that is a null-string will use pattern based on
+ device's prompt (unless expect_string argument is passed in via
+ kwargs.
+
+ """
+ output = ""
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+
+ default_expect_string = kwargs.pop("expect_string", None)
+ if not default_expect_string:
+ auto_find_prompt = kwargs.get("auto_find_prompt", True)
+ default_expect_string = self._prompt_handler(auto_find_prompt)
+
+ if commands and isinstance(commands[0], str):
+ # If list of commands just send directly using default_expect_string (probably prompt)
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_str(
+ cmd, expect_string=default_expect_string, **kwargs
+ )
+ else:
+ # If list of lists, then first element is cmd and second element is expect_string
+ for cmd_item in commands:
+ assert not isinstance(cmd_item, str)
+ cmd, expect_string = cmd_item
+ if not expect_string:
+ expect_string = default_expect_string
+ output += self._send_command_str(
+ cmd, expect_string=expect_string, **kwargs
+ )
+ return output
This method handles some differences that occur between various devices
early on in the session.
In general, it should include:
-self._test_channel_read()
+self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
-self.disable_paging()
self.set_terminal_width()
-self.clear_buffer()
+self.disable_paging()
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -5862,24 +6587,19 @@
Methods
early on in the session.
In general, it should include:
- self._test_channel_read()
+ self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
- self.disable_paging()
self.set_terminal_width()
- self.clear_buffer()
+ self.disable_paging()
"""
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
- self.disable_paging()
-
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
-
:param command: Command string to send to the device
-:type command: str
-
:param delay_factor: See init: global_delay_factor
-:type delay_factor: int
+
:param command: Command string to send to the device
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
Source code
def set_terminal_width(
- self, command="", delay_factor=1, cmd_verify=False, pattern=None
-):
+ self,
+ command: str = "",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = False,
+ pattern: Optional[str] = None,
+) -> str:
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
if not command:
return ""
- delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
+
# Avoid cmd_verify here as terminal width must be set before doing cmd_verify
if cmd_verify and self.global_cmd_verify is not False:
output = self.read_until_pattern(pattern=re.escape(command.strip()))
@@ -5974,13 +6712,13 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handler for devices like WLC, Extreme ERS that throw up characters prior to login."""
pass
@@ -6015,18 +6753,20 @@
Methods
ESC[2J
Code erase display
ESC[00;32m
-Color Green (30 to 37 are different colors) more general pattern is
-ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+Color Green (30 to 37 are different colors)
ESC[6n
Get cursor position
ESC[1D
-Move cursor position leftward by x characters (1 in this case)
+Move cursor position leftward by x characters (1 in this case)
+ESC[9999B
+Move cursor down N-lines (very large value is attempt to move to the
+very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
:param string_buffer: The string to be processed to remove ANSI escape codes
:type string_buffer: str
def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Remove any ANSI (VT100) ESC codes from the output
@@ -6047,10 +6787,11 @@
Methods
ESC[?6l Reset mode screen with options 640 x 200 monochrome (graphics)
ESC[?7l Disable line wrapping
ESC[2J Code erase display
- ESC[00;32m Color Green (30 to 37 are different colors) more general pattern is
- ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+ ESC[00;32m Color Green (30 to 37 are different colors)
ESC[6n Get cursor position
ESC[1D Move cursor position leftward by x characters (1 in this case)
+ ESC[9999B Move cursor down N-lines (very large value is attempt to move to the
+ very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
@@ -6072,7 +6813,8 @@
def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
:param a_string: Returned string from device
@@ -6183,6 +6936,7 @@
Methods
"""
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
+
if self.base_prompt in last_line:
return self.RESPONSE_RETURN.join(response_list[:-1])
else:
@@ -6190,51 +6944,41 @@
Telnet login. Can be username/password or just password.
-
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
-:type pri_prompt_terminator: str
-
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
-:type alt_prompt_terminator: str
-
:param username_pattern: Pattern used to identify the username prompt
-:type username_pattern: str
-
:param delay_factor: See init: global_delay_factor
-:type delay_factor: int
-
:param max_loops: Controls the wait time in conjunction with the delay_factor
-(default: 20)
+
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
+
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
+
:param username_pattern: Pattern used to identify the username prompt
+
:param delay_factor: See init: global_delay_factor
+
:param max_loops: Controls the wait time in conjunction with the delay_factor
Source code
def telnet_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
-):
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+) -> str:
"""Telnet login. Can be username/password or just password.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param username_pattern: Pattern used to identify the username prompt
- :type username_pattern: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
:param max_loops: Controls the wait time in conjunction with the delay_factor
- (default: 20)
"""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
+ # Revert telnet_login back to old speeds/delays
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -6260,6 +7004,7 @@
Methods
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -6279,6 +7024,7 @@
Methods
time.sleep(0.5 * delay_factor)
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -6294,6 +7040,7 @@
Methods
return return_msg
msg = f"Login failed: {self.host}"
+ assert self.remote_conn is not None
self.remote_conn.close()
raise NetmikoAuthenticationException(msg)
@@ -6302,30 +7049,79 @@
Methods
def write_channel(self, out_data)
-
Generic handler that will write to both SSH and telnet channel.
+
Generic method that will write data out the channel.
:param out_data: data to be written to the channel
-:type out_data: str (can be either unicode/byte string)
+:type out_data: strSource code
-
def write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+
@lock_channel
+@log_writes
+def write_channel(self, out_data: str) -> None:
+ """Generic method that will write data out the channel.
:param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
+ :type out_data: str
"""
- self._lock_netmiko_session()
- try:
- self._write_channel(out_data)
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+ self.channel.write_channel(out_data)
+
+
+
+
+
+class SecretsFilter
+(no_log=None)
+
+
+
Filter instances are used to perform arbitrary filtering of LogRecords.
+
Loggers and Handlers can optionally use Filter instances to filter
+records as desired. The base filter class only allows events which are
+below a certain point in the logger hierarchy. For example, a filter
+initialized with "A.B" will allow events logged by loggers "A.B",
+"A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
+initialized with the empty string, all events are passed.
+
Initialize a filter.
+
Initialize with the name of the logger which, together with its
+children, will have its events allowed through the filter. If no
+name is specified, allow every event.
+
+Source code
+
class SecretsFilter(logging.Filter):
+ def __init__(self, no_log: Optional[Dict[Any, str]] = None) -> None:
+ self.no_log = no_log
+
+ def filter(self, record: logging.LogRecord) -> bool:
+ """Removes secrets (no_log) from messages"""
+ if self.no_log:
+ for hidden_data in self.no_log.values():
+ record.msg = record.msg.replace(hidden_data, "********")
+ return True
+
+
Ancestors
+
+
logging.Filter
+
+
Methods
+
+
+def filter(self, record)
+
+
+
Removes secrets (no_log) from messages
+
+Source code
+
def filter(self, record: logging.LogRecord) -> bool:
+ """Removes secrets (no_log) from messages"""
+ if self.no_log:
+ for hidden_data in self.no_log.values():
+ record.msg = record.msg.replace(hidden_data, "********")
+ return True
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implements support for Broadcom Icos devices.
@@ -87,131 +91,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string=")#"):
+
def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
- return super().check_config_mode(check_string=check_string)
Implements support for Broadcom Icos devices.
@@ -55,131 +55,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string=")#"):
+
def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
- return super().check_config_mode(check_string=check_string)
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
-
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
-
"""Calix B6 SSH Driver for Netmiko"""
+from typing import Any
import time
from os import path
from paramiko import SSHClient
from netmiko.cisco_base_connection import CiscoSSHConnection
-
-
-class SSHClient_noauth(SSHClient):
- """Set noauth when manually handling SSH authentication."""
-
- def _auth(self, username, *args):
- self._transport.auth_none(username)
- return
+from netmiko.ssh_auth import SSHClient_noauth
+from netmiko.exceptions import NetmikoTimeoutException
class CalixB6Base(CiscoSSHConnection):
"""Common methods for Calix B6, both SSH and Telnet."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> Any:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ 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()
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Calix B6 presents with the following on login:
login as:
Password: ****
"""
- delay_factor = self.select_delay_factor(delay_factor)
- i = 0
- time.sleep(delay_factor * 0.25)
- output = ""
- while i <= 12:
- output = self.read_channel()
+ new_data = ""
+ time.sleep(0.1)
+ start = time.time()
+ login_timeout = 20
+ while time.time() - start < login_timeout:
+ output = self.read_channel() if not new_data else new_data
+ new_data = ""
if output:
if "login as:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
- time.sleep(delay_factor * 0.5)
+ time.sleep(0.1)
else:
- self.write_channel(self.RETURN)
- time.sleep(delay_factor * 1)
- i += 1
-
- def check_config_mode(self, check_string=")#", pattern=""):
+ # No new data...sleep longer
+ time.sleep(0.5)
+ new_data = self.read_channel()
+ # If still no data, send an <enter>
+ if not new_data:
+ self.write_channel(self.RETURN)
+ else: # no-break
+ msg = """
+Login process failed to Calix B6 device. Unable to login in {login_timeout} seconds.
+"""
+ raise NetmikoTimeoutException(msg)
+
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode"""
return super().check_config_mode(check_string=check_string)
- def save_config(self, cmd="copy run start", confirm=False, confirm_response=""):
+ def save_config(
+ self,
+ cmd: str = "copy run start",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
)
@@ -101,12 +109,12 @@
Module netmiko.calix.calix_b6
the username/password.
"""
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
# If not using SSH keys, we use noauth
if not self.use_keys:
- remote_conn_pre = SSHClient_noauth()
+ remote_conn_pre: SSHClient = SSHClient_noauth()
else:
remote_conn_pre = SSHClient()
@@ -146,183 +154,169 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CalixB6Base(CiscoSSHConnection):
"""Common methods for Calix B6, both SSH and Telnet."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> Any:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ 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()
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Calix B6 presents with the following on login:
login as:
Password: ****
"""
- delay_factor = self.select_delay_factor(delay_factor)
- i = 0
- time.sleep(delay_factor * 0.25)
- output = ""
- while i <= 12:
- output = self.read_channel()
+ new_data = ""
+ time.sleep(0.1)
+ start = time.time()
+ login_timeout = 20
+ while time.time() - start < login_timeout:
+ output = self.read_channel() if not new_data else new_data
+ new_data = ""
if output:
if "login as:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
- time.sleep(delay_factor * 0.5)
+ time.sleep(0.1)
else:
- self.write_channel(self.RETURN)
- time.sleep(delay_factor * 1)
- i += 1
-
- def check_config_mode(self, check_string=")#", pattern=""):
+ # No new data...sleep longer
+ time.sleep(0.5)
+ new_data = self.read_channel()
+ # If still no data, send an <enter>
+ if not new_data:
+ self.write_channel(self.RETURN)
+ else: # no-break
+ msg = """
+Login process failed to Calix B6 device. Unable to login in {login_timeout} seconds.
+"""
+ raise NetmikoTimeoutException(msg)
+
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode"""
return super().check_config_mode(check_string=check_string)
- def save_config(self, cmd="copy run start", confirm=False, confirm_response=""):
+ def save_config(
+ self,
+ cmd: str = "copy run start",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -600,12 +575,12 @@
Inherited members
the username/password.
"""
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
# If not using SSH keys, we use noauth
if not self.use_keys:
- remote_conn_pre = SSHClient_noauth()
+ remote_conn_pre: SSHClient = SSHClient_noauth()
else:
remote_conn_pre = SSHClient()
@@ -634,9 +609,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -190,12 +163,12 @@
Classes
the username/password.
"""
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
# If not using SSH keys, we use noauth
if not self.use_keys:
- remote_conn_pre = SSHClient_noauth()
+ remote_conn_pre: SSHClient = SSHClient_noauth()
else:
remote_conn_pre = SSHClient()
@@ -224,9 +197,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implement methods for interacting with CROS network devices.
@@ -147,163 +158,151 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implement methods for interacting with CROS network devices.
@@ -53,163 +53,151 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
from typing import Any, Optional
+from abc import ABC, abstractmethod
+import paramiko
+import telnetlib
+import serial
+
+from netmiko.utilities import write_bytes
+from netmiko.netmiko_globals import MAX_BUFFER
+from netmiko.exceptions import ReadException, WriteException
+
+
+class Channel(ABC):
+ @abstractmethod
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """Create the object."""
+ pass
+
+ # @abstractmethod
+ # def __repr__(self) -> str:
+ # """String representation of the object."""
+ # pass
+ #
+ # @abstractmethod
+ # def open(self, width: int = 511, height: int = 1000) -> None:
+ # """Create the underlying connection."""
+ # pass
+ #
+ # @abstractmethod
+ # def close(self) -> None:
+ # """Close the underlying connection."""
+ # pass
+ #
+ # @abstractmethod
+ # def login(self) -> None:
+ # """Handle the channel login process for any channel that requires it."""
+ # pass
+
+ @abstractmethod
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ pass
+
+ @abstractmethod
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ pass
+
+ @abstractmethod
+ def write_channel(self, out_data: str) -> None:
+ """Write data down the channel."""
+ pass
+
+ # @abstractmethod
+ # def is_alive(self) -> bool:
+ # """Is the channel alive."""
+ # pass
+
+
+class SSHChannel(Channel):
+ def __init__(self, conn: Optional[paramiko.Channel], encoding: str) -> None:
+ """
+ Placeholder __init__ method so that reading and writing can be moved to the
+ channel class.
+ """
+ self.remote_conn = conn
+ # FIX: move encoding to GlobalState object?
+ self.encoding = encoding
+
+ def write_channel(self, out_data: str) -> None:
+ if self.remote_conn is None:
+ raise WriteException(
+ "Attempt to write data, but there is no active channel."
+ )
+ self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))
+
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ output = ""
+ if self.remote_conn.recv_ready():
+ outbuf = self.remote_conn.recv(MAX_BUFFER)
+ if len(outbuf) == 0:
+ raise ReadException("Channel stream closed by remote device.")
+ output += outbuf.decode("utf-8", "ignore")
+ return output
+
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ output = ""
+ while True:
+ new_output = self.read_buffer()
+ output += new_output
+ if new_output == "":
+ break
+ return output
+
+
+class TelnetChannel(Channel):
+ def __init__(self, conn: Optional[telnetlib.Telnet], encoding: str) -> None:
+ """
+ Placeholder __init__ method so that reading and writing can be moved to the
+ channel class.
+ """
+ self.remote_conn = conn
+ # FIX: move encoding to GlobalState object?
+ self.encoding = encoding
+
+ def write_channel(self, out_data: str) -> None:
+ if self.remote_conn is None:
+ raise WriteException(
+ "Attempt to write data, but there is no active channel."
+ )
+ self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
+
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ raise NotImplementedError
+
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ return self.remote_conn.read_very_eager().decode("utf-8", "ignore")
+
+
+class SerialChannel(Channel):
+ def __init__(self, conn: Optional[serial.Serial], encoding: str) -> None:
+ """
+ Placeholder __init__ method so that reading and writing can be moved to the
+ channel class.
+ """
+ self.remote_conn = conn
+ # FIX: move encoding to GlobalState object?
+ self.encoding = encoding
+
+ def write_channel(self, out_data: str) -> None:
+ if self.remote_conn is None:
+ raise WriteException(
+ "Attempt to write data, but there is no active channel."
+ )
+ self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
+ self.remote_conn.flush()
+
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ if self.remote_conn.in_waiting > 0:
+ output = self.remote_conn.read(self.remote_conn.in_waiting).decode(
+ "utf-8", "ignore"
+ )
+ assert isinstance(output, str)
+ return output
+ else:
+ return ""
+
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ output = ""
+ while self.remote_conn.in_waiting > 0:
+ output += self.read_buffer()
+ return output
+
+
+
+
+
+
+
+
+
+
Classes
+
+
+class Channel
+(*args, **kwargs)
+
+
+
Helper class that provides a standard way to create an ABC using
+inheritance.
+
Create the object.
+
+Source code
+
class Channel(ABC):
+ @abstractmethod
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ """Create the object."""
+ pass
+
+ # @abstractmethod
+ # def __repr__(self) -> str:
+ # """String representation of the object."""
+ # pass
+ #
+ # @abstractmethod
+ # def open(self, width: int = 511, height: int = 1000) -> None:
+ # """Create the underlying connection."""
+ # pass
+ #
+ # @abstractmethod
+ # def close(self) -> None:
+ # """Close the underlying connection."""
+ # pass
+ #
+ # @abstractmethod
+ # def login(self) -> None:
+ # """Handle the channel login process for any channel that requires it."""
+ # pass
+
+ @abstractmethod
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ pass
+
+ @abstractmethod
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ pass
+
+ @abstractmethod
+ def write_channel(self, out_data: str) -> None:
+ """Write data down the channel."""
+ pass
@abstractmethod
+def read_buffer(self) -> str:
+ """Single read of available data."""
+ pass
+
+
+
+def read_channel(self)
+
+
+
Read all of the available data from the channel.
+
+Source code
+
@abstractmethod
+def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ pass
+
+
+
+def write_channel(self, out_data)
+
+
+
Write data down the channel.
+
+Source code
+
@abstractmethod
+def write_channel(self, out_data: str) -> None:
+ """Write data down the channel."""
+ pass
+
+
+
+
+
+class SSHChannel
+(conn, encoding)
+
+
+
Helper class that provides a standard way to create an ABC using
+inheritance.
+
Placeholder init method so that reading and writing can be moved to the
+channel class.
+
+Source code
+
class SSHChannel(Channel):
+ def __init__(self, conn: Optional[paramiko.Channel], encoding: str) -> None:
+ """
+ Placeholder __init__ method so that reading and writing can be moved to the
+ channel class.
+ """
+ self.remote_conn = conn
+ # FIX: move encoding to GlobalState object?
+ self.encoding = encoding
+
+ def write_channel(self, out_data: str) -> None:
+ if self.remote_conn is None:
+ raise WriteException(
+ "Attempt to write data, but there is no active channel."
+ )
+ self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))
+
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ output = ""
+ if self.remote_conn.recv_ready():
+ outbuf = self.remote_conn.recv(MAX_BUFFER)
+ if len(outbuf) == 0:
+ raise ReadException("Channel stream closed by remote device.")
+ output += outbuf.decode("utf-8", "ignore")
+ return output
+
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ output = ""
+ while True:
+ new_output = self.read_buffer()
+ output += new_output
+ if new_output == "":
+ break
+ return output
Helper class that provides a standard way to create an ABC using
+inheritance.
+
Placeholder init method so that reading and writing can be moved to the
+channel class.
+
+Source code
+
class SerialChannel(Channel):
+ def __init__(self, conn: Optional[serial.Serial], encoding: str) -> None:
+ """
+ Placeholder __init__ method so that reading and writing can be moved to the
+ channel class.
+ """
+ self.remote_conn = conn
+ # FIX: move encoding to GlobalState object?
+ self.encoding = encoding
+
+ def write_channel(self, out_data: str) -> None:
+ if self.remote_conn is None:
+ raise WriteException(
+ "Attempt to write data, but there is no active channel."
+ )
+ self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
+ self.remote_conn.flush()
+
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ if self.remote_conn.in_waiting > 0:
+ output = self.remote_conn.read(self.remote_conn.in_waiting).decode(
+ "utf-8", "ignore"
+ )
+ assert isinstance(output, str)
+ return output
+ else:
+ return ""
+
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ output = ""
+ while self.remote_conn.in_waiting > 0:
+ output += self.read_buffer()
+ return output
Helper class that provides a standard way to create an ABC using
+inheritance.
+
Placeholder init method so that reading and writing can be moved to the
+channel class.
+
+Source code
+
class TelnetChannel(Channel):
+ def __init__(self, conn: Optional[telnetlib.Telnet], encoding: str) -> None:
+ """
+ Placeholder __init__ method so that reading and writing can be moved to the
+ channel class.
+ """
+ self.remote_conn = conn
+ # FIX: move encoding to GlobalState object?
+ self.encoding = encoding
+
+ def write_channel(self, out_data: str) -> None:
+ if self.remote_conn is None:
+ raise WriteException(
+ "Attempt to write data, but there is no active channel."
+ )
+ self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
+
+ def read_buffer(self) -> str:
+ """Single read of available data."""
+ raise NotImplementedError
+
+ def read_channel(self) -> str:
+ """Read all of the available data from the channel."""
+ if self.remote_conn is None:
+ raise ReadException("Attempt to read, but there is no active channel.")
+ return self.remote_conn.read_very_eager().decode("utf-8", "ignore")
Implements methods for communicating with Check Point Gaia
@@ -78,195 +68,135 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CheckPointGaiaSSH(BaseConnection):
+
class CheckPointGaiaSSH(NoConfig, BaseConnection):
"""
Implements methods for communicating with Check Point Gaia
firewalls.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.disable_paging(command="set clienv rows 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def config_mode(self, config_command=""):
- """No config mode for Check Point devices."""
- return ""
-
- def exit_config_mode(self, exit_config=""):
- """No config mode for Check Point devices."""
- return ""
- def save_config(self, *args, **kwargs):
- """Not Implemented"""
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
raise NotImplementedError
def config_mode(self, config_command=""):
- """No config mode for Check Point devices."""
- return ""
-
-
-
-def exit_config_mode(self, exit_config='')
-
-
-
No config mode for Check Point devices.
-
-Source code
-
def exit_config_mode(self, exit_config=""):
- """No config mode for Check Point devices."""
- return ""
-
-
def session_preparation(self)
@@ -275,18 +205,15 @@
Methods
Set the base prompt for interaction ('>').
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- self.disable_paging(command="set clienv rows 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
Implements methods for communicating with Check Point Gaia
@@ -54,195 +54,135 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CheckPointGaiaSSH(BaseConnection):
+
class CheckPointGaiaSSH(NoConfig, BaseConnection):
"""
Implements methods for communicating with Check Point Gaia
firewalls.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.disable_paging(command="set clienv rows 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def config_mode(self, config_command=""):
- """No config mode for Check Point devices."""
- return ""
- def exit_config_mode(self, exit_config=""):
- """No config mode for Check Point devices."""
- return ""
-
- def save_config(self, *args, **kwargs):
- """Not Implemented"""
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
raise NotImplementedError
def config_mode(self, config_command=""):
- """No config mode for Check Point devices."""
- return ""
-
-
-
-def exit_config_mode(self, exit_config='')
-
-
-
No config mode for Check Point devices.
-
-Source code
-
def exit_config_mode(self, exit_config=""):
- """No config mode for Check Point devices."""
- return ""
-
-
def session_preparation(self)
@@ -251,18 +191,15 @@
Methods
Set the base prompt for interaction ('>').
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- self.disable_paging(command="set clienv rows 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
return int(space_avail) * 1024
- def check_file_exists(self, remote_cmd=""):
+ def check_file_exists(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = f"file ls {self.file_system}/{self.dest_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
search_string = re.escape(f"{self.file_system}/{self.dest_file}")
if "ERROR" in remote_out:
return False
@@ -179,8 +158,12 @@
Module netmiko.ciena.ciena_saos
raise ValueError("Unexpected output from check_file_exists")
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_file_size(self, remote_cmd="", remote_file=None):
+ def remote_file_size(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -193,7 +176,7 @@
Module netmiko.ciena.ciena_saos
if not remote_cmd:
remote_cmd = f"file ls -l {remote_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
if "No such file or directory" in remote_out:
raise IOError("Unable to find file on remote system")
@@ -211,7 +194,7 @@
Module netmiko.ciena.ciena_saos
"Search pattern not found for remote file size during SCP transfer."
)
- def remote_md5(self, base_cmd="", remote_file=None):
+ def remote_md5(self, base_cmd: str = "", remote_file: Optional[str] = None) -> str:
"""Calculate remote MD5 and returns the hash.
This command can be CPU intensive on the remote device.
@@ -227,17 +210,17 @@
Implements methods for interacting Ciena Saos devices.
-
Disables enable(), check_enable_mode(), config_mode() and
-check_config_mode()
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
return int(space_avail) * 1024
- def check_file_exists(self, remote_cmd=""):
+ def check_file_exists(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = f"file ls {self.file_system}/{self.dest_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
search_string = re.escape(f"{self.file_system}/{self.dest_file}")
if "ERROR" in remote_out:
return False
@@ -673,8 +547,12 @@
Inherited members
raise ValueError("Unexpected output from check_file_exists")
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_file_size(self, remote_cmd="", remote_file=None):
+ def remote_file_size(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -687,7 +565,7 @@
Inherited members
if not remote_cmd:
remote_cmd = f"file ls -l {remote_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
if "No such file or directory" in remote_out:
raise IOError("Unable to find file on remote system")
@@ -705,7 +583,7 @@
Inherited members
"Search pattern not found for remote file size during SCP transfer."
)
- def remote_md5(self, base_cmd="", remote_file=None):
+ def remote_md5(self, base_cmd: str = "", remote_file: Optional[str] = None) -> str:
"""Calculate remote MD5 and returns the hash.
This command can be CPU intensive on the remote device.
@@ -721,17 +599,17 @@
Implements methods for interacting Ciena Saos devices.
-
Disables enable(), check_enable_mode(), config_mode() and
-check_config_mode()
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implements methods for interacting Ciena Saos devices.
-
Disables enable(), check_enable_mode(), config_mode() and
-check_config_mode()
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CienaSaosTelnet(CienaSaosBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
return int(space_avail) * 1024
- def check_file_exists(self, remote_cmd=""):
+ def check_file_exists(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = f"file ls {self.file_system}/{self.dest_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
search_string = re.escape(f"{self.file_system}/{self.dest_file}")
if "ERROR" in remote_out:
return False
@@ -133,8 +133,12 @@
Classes
raise ValueError("Unexpected output from check_file_exists")
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_file_size(self, remote_cmd="", remote_file=None):
+ def remote_file_size(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -147,7 +151,7 @@
Classes
if not remote_cmd:
remote_cmd = f"file ls -l {remote_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
if "No such file or directory" in remote_out:
raise IOError("Unable to find file on remote system")
@@ -165,7 +169,7 @@
Classes
"Search pattern not found for remote file size during SCP transfer."
)
- def remote_md5(self, base_cmd="", remote_file=None):
+ def remote_md5(self, base_cmd: str = "", remote_file: Optional[str] = None) -> str:
"""Calculate remote MD5 and returns the hash.
This command can be CPU intensive on the remote device.
@@ -181,17 +185,17 @@
Implements methods for interacting Ciena Saos devices.
-
Disables enable(), check_enable_mode(), config_mode() and
-check_config_mode()
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implements methods for interacting Ciena Saos devices.
-
Disables enable(), check_enable_mode(), config_mode() and
-check_config_mode()
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CienaSaosTelnet(CienaSaosBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
"""Subclass specific to Cisco ASA."""
+from typing import Any, Union, List, Dict, Optional
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection, CiscoFileTransfer
-from netmiko.ssh_exception import NetmikoAuthenticationException
+from netmiko.exceptions import NetmikoAuthenticationException
class CiscoAsaSSH(CiscoSSHConnection):
"""Subclass specific to Cisco ASA."""
- def __init__(self, *args, **kwargs):
- kwargs.setdefault("fast_cli", True)
- kwargs.setdefault("_legacy_mode", False)
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.setdefault("allow_auto_change", True)
return super().__init__(*args, **kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# Make sure the ASA is ready
@@ -67,21 +66,25 @@
Module netmiko.cisco.cisco_asa_ssh
self.set_base_prompt()
- def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[>\#]"
+ ) -> bool:
return super().check_config_mode(check_string=check_string, pattern=pattern)
def enable(
self,
- cmd="enable",
- pattern="ssword",
- enable_pattern=r"\#",
- re_flags=re.IGNORECASE,
- ):
+ cmd: str = "enable",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = r"\#",
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
return super().enable(
cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
)
- def send_command_timing(self, *args, **kwargs):
+ def send_command_timing(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -95,7 +98,9 @@
Module netmiko.cisco.cisco_asa_ssh
self.set_base_prompt()
return output
- def send_command(self, *args, **kwargs):
+ def send_command(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -117,11 +122,7 @@
Module netmiko.cisco.cisco_asa_ssh
return output
- def send_command_expect(self, *args, **kwargs):
- """Backwards compaitibility."""
- return self.send_command(*args, **kwargs)
-
- def set_base_prompt(self, *args, **kwargs):
+ def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Cisco ASA in multi-context mode needs to have the base prompt updated
(if you switch contexts i.e. 'changeto')
@@ -135,8 +136,10 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoAsaSSH(CiscoSSHConnection):
"""Subclass specific to Cisco ASA."""
- def __init__(self, *args, **kwargs):
- kwargs.setdefault("fast_cli", True)
- kwargs.setdefault("_legacy_mode", False)
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.setdefault("allow_auto_change", True)
return super().__init__(*args, **kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# Make sure the ASA is ready
@@ -418,21 +396,25 @@
Inherited members
self.set_base_prompt()
- def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[>\#]"
+ ) -> bool:
return super().check_config_mode(check_string=check_string, pattern=pattern)
def enable(
self,
- cmd="enable",
- pattern="ssword",
- enable_pattern=r"\#",
- re_flags=re.IGNORECASE,
- ):
+ cmd: str = "enable",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = r"\#",
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
return super().enable(
cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
)
- def send_command_timing(self, *args, **kwargs):
+ def send_command_timing(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -446,7 +428,9 @@
Inherited members
self.set_base_prompt()
return output
- def send_command(self, *args, **kwargs):
+ def send_command(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -468,11 +452,7 @@
Inherited members
return output
- def send_command_expect(self, *args, **kwargs):
- """Backwards compaitibility."""
- return self.send_command(*args, **kwargs)
-
- def set_base_prompt(self, *args, **kwargs):
+ def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Cisco ASA in multi-context mode needs to have the base prompt updated
(if you switch contexts i.e. 'changeto')
@@ -486,8 +466,10 @@
def send_command(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -650,18 +642,6 @@
def send_command_timing(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -692,7 +674,7 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# Make sure the ASA is ready
@@ -731,7 +713,7 @@
Methods
happens the trailing '(config*' needs stripped off.
Source code
-
def set_base_prompt(self, *args, **kwargs):
+
def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Cisco ASA in multi-context mode needs to have the base prompt updated
(if you switch contexts i.e. 'changeto')
@@ -744,7 +726,9 @@
Methods
if match:
# strip off (conf.* from base_prompt
self.base_prompt = match.group(1)
- return self.base_prompt
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CiscoFtdSSH(CiscoSSHConnection):
+
class CiscoFtdSSH(NoEnable, NoConfig, CiscoSSHConnection):
"""Subclass specific to Cisco FTD."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- def send_config_set(self, *args, **kwargs):
+ def send_config_set(self, *args: Any, **kwargs: Any) -> str:
"""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"""
+ def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
+ """Canot change config on FTD via ssh"""
return False
def send_config_set(self, *args: Any, **kwargs: Any) -> str:
"""Canot change config on FTD via ssh"""
raise NotImplementedError
@@ -286,9 +224,9 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.socket_timeout = socket_timeout
@staticmethod
- def _read_file(file_name):
+ def _read_file(file_name: str) -> str:
with io.open(file_name, "rt", encoding="utf-8") as f:
return f.read()
@staticmethod
- def _tcl_newline_rationalize(tcl_string):
+ def _tcl_newline_rationalize(tcl_string: str) -> str:
r"""
When using put inside a TCL {} section the newline is considered a new TCL
statement and causes a missing curly-brace message. Convert "\n" to "\r". TCL
@@ -158,17 +164,22 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoIosBase(CiscoBaseConnection):
"""Common Methods for IOS (both SSH and telnet)."""
- def __init__(self, *args, **kwargs):
- # Cisco-IOS 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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
cmd = "terminal width 511"
self.set_terminal_width(command=cmd, pattern=cmd)
self.disable_paging()
self.set_base_prompt()
- def check_config_mode(self, check_string=")#", pattern="#"):
+ def check_config_mode(self, check_string: str = ")#", pattern: str = r"#") -> bool:
"""
Checks if the device is in configuration mode or not.
@@ -441,7 +427,9 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
cmd = "terminal width 511"
self.set_terminal_width(command=cmd, pattern=cmd)
@@ -500,9 +490,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
self.socket_timeout = socket_timeout
@staticmethod
- def _read_file(file_name):
+ def _read_file(file_name: str) -> str:
with io.open(file_name, "rt", encoding="utf-8") as f:
return f.read()
@staticmethod
- def _tcl_newline_rationalize(tcl_string):
+ def _tcl_newline_rationalize(tcl_string: str) -> str:
r"""
When using put inside a TCL {} section the newline is considered a new TCL
statement and causes a missing curly-brace message. Convert "\n" to "\r". TCL
@@ -1260,17 +1176,22 @@
from typing import Any, Optional, Callable
+import re
import os
+from netmiko.base_connection import BaseConnection
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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
# NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
@@ -46,46 +42,45 @@
Module netmiko.cisco.cisco_nxos_ssh
self.disable_paging()
self.set_base_prompt()
- def normalize_linefeeds(self, a_string):
+ def normalize_linefeeds(self, a_string: str) -> str:
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n\r|\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
return newline.sub(self.RESPONSE_RETURN, a_string).replace("\r", "\n")
- def check_config_mode(self, check_string=")#", pattern="#"):
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string, pattern=pattern)
def save_config(
self,
- cmd="copy running-config startup-config",
- confirm=False,
- confirm_response="",
- ):
+ cmd: str = "copy running-config startup-config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
self.enable()
+ output = ""
if confirm:
- output = self.send_command_timing(
+ output += self._send_command_timing_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
if confirm_response:
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
confirm_response, strip_prompt=False, strip_command=False
)
else:
# Send enter by default
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
self.RETURN, strip_prompt=False, strip_command=False
)
else:
# NX-OS is very slow on save_config ensure it waits long enough.
- # FIX: this is a hack as delay_factor will be set to .1 via fast_cli=True in
- # send_command so increase max_loops.
- output = self.send_command(
+ output += self._send_command_str(
command_string=cmd,
strip_prompt=False,
strip_command=False,
- max_loops=5000,
+ read_timeout=100,
)
return output
@@ -95,20 +90,24 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
# NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
@@ -505,46 +495,45 @@
Inherited members
self.disable_paging()
self.set_base_prompt()
- def normalize_linefeeds(self, a_string):
+ def normalize_linefeeds(self, a_string: str) -> str:
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n\r|\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
return newline.sub(self.RESPONSE_RETURN, a_string).replace("\r", "\n")
- def check_config_mode(self, check_string=")#", pattern="#"):
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string, pattern=pattern)
def save_config(
self,
- cmd="copy running-config startup-config",
- confirm=False,
- confirm_response="",
- ):
+ cmd: str = "copy running-config startup-config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
self.enable()
+ output = ""
if confirm:
- output = self.send_command_timing(
+ output += self._send_command_timing_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
if confirm_response:
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
confirm_response, strip_prompt=False, strip_command=False
)
else:
# Send enter by default
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
self.RETURN, strip_prompt=False, strip_command=False
)
else:
# NX-OS is very slow on save_config ensure it waits long enough.
- # FIX: this is a hack as delay_factor will be set to .1 via fast_cli=True in
- # send_command so increase max_loops.
- output = self.send_command(
+ output += self._send_command_str(
command_string=cmd,
strip_prompt=False,
strip_command=False,
- max_loops=5000,
+ read_timeout=100,
)
return output
@@ -563,7 +552,7 @@
Methods
Checks if the device is in configuration mode or not.
def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string, pattern=pattern)
@@ -579,7 +568,7 @@
Methods
's in the text.
Source code
-
def normalize_linefeeds(self, a_string):
+
def normalize_linefeeds(self, a_string: str) -> str:
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n\r|\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
@@ -593,7 +582,7 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
# NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
@@ -613,9 +602,8 @@
import time
-from netmiko.cisco_base_connection import CiscoSSHConnection
+
from netmiko.cisco_base_connection import CiscoSSHConnection
-class CiscoS300SSH(CiscoSSHConnection):
+class CiscoS300Base(CiscoSSHConnection):
"""
Support for Cisco SG300 series of devices.
@@ -36,20 +35,36 @@
+ )
+
+
+class CiscoS300SSH(CiscoS300Base):
+ pass
+
+
+class CiscoS300Telnet(CiscoS300Base):
+ """
+ Support for Cisco SG300 series of devices, with telnet.
+ Note: can be used with Sx200 series, with telnet enabled.
+ """
+
+ pass
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CiscoS300SSH(CiscoSSHConnection):
+
class CiscoS300Base(CiscoSSHConnection):
"""
Support for Cisco SG300 series of devices.
@@ -212,17 +200,20 @@
Note, must configure the following to disable SG300 from prompting for username twice:
+
configure terminal
+ip ssh password-auth
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
Support for Cisco SG300 series of devices, with telnet.
+Note: can be used with Sx200 series, with telnet enabled.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
+
+Source code
+
class CiscoS300Telnet(CiscoS300Base):
+ """
+ Support for Cisco SG300 series of devices, with telnet.
+ Note: can be used with Sx200 series, with telnet enabled.
+ """
+
+ pass
CiscoTpTcCeSSH Class
Class to manage Cisco Telepresence Endpoint on TC/CE software release. Also working for Cisco
Expressway/VCS
-
Written by Ahmad Barrin
+
Written by Ahmad Barrin
+Updated by Kirk Byers
Source code
"""
@@ -34,23 +35,25 @@
Module netmiko.cisco.cisco_tp_tcce
Expressway/VCS
Written by Ahmad Barrin
+Updated by Kirk Byers
"""
+from typing import Any, Union, List, Dict
import time
import re
from netmiko.cisco_base_connection import CiscoSSHConnection
class CiscoTpTcCeSSH(CiscoSSHConnection):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""Paging is disabled by default."""
return ""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -62,6 +65,8 @@
Module netmiko.cisco.cisco_tp_tcce
self.disable_paging()
self.set_terminal_width()
"""
+ # Could not work out what the CLI looked like. It would be good to switch to
+ # a pattern on the _test_channel_read() call.
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
@@ -70,16 +75,16 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoTpTcCeSSH(CiscoSSHConnection):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""Paging is disabled by default."""
return ""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -282,6 +262,8 @@
Classes
self.disable_paging()
self.set_terminal_width()
"""
+ # Could not work out what the CLI looked like. It would be good to switch to
+ # a pattern on the _test_channel_read() call.
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
@@ -290,16 +272,16 @@
detected. The current network device prompt will be determined automatically.
Source code
-
def send_command(self, *args, **kwargs):
+
def send_command(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""
Send command to network device retrieve output until router_prompt or expect_string
@@ -418,7 +404,7 @@
Methods
self.set_terminal_width()
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -430,6 +416,8 @@
Methods
self.disable_paging()
self.set_terminal_width()
"""
+ # Could not work out what the CLI looked like. It would be good to switch to
+ # a pattern on the _test_channel_read() call.
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
@@ -446,7 +434,7 @@
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
+
+Source code
+
class CiscoViptelaSSH(CiscoSSHConnection):
+ """Subclass specific to Cisco Viptela."""
+
+ def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.disable_paging(command="paginate false")
+
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
+ """Checks if the device is in configuration mode or not."""
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
+
+ def commit(self, confirm: bool = False, confirm_response: str = "") -> str:
+ cmd = "commit"
+ return super().save_config(
+ cmd=cmd, confirm=confirm, confirm_response=confirm_response
+ )
+
+ def config_mode(
+ self,
+ config_command: str = "conf terminal",
+ pattern: str = "",
+ re_flags: int = 0,
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
+
+ def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = False,
+ **kwargs: Any,
+ ) -> str:
+ return super().send_config_set(
+ config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ )
+
+ def exit_config_mode(self, exit_config: str = "end", pattern: str = r"#") -> str:
+ """
+ Exit from configuration mode.
+
+ Viptela might have the following in the output (if no 'commit()' occurred.
+
+ Uncommitted changes found, commit them? [yes/no/CANCEL]
+ """
+ output = ""
+ if self.check_config_mode():
+ 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 not re.search(pattern, output, flags=re.M):
+ uncommit_pattern = r"Uncommitted changes found"
+ new_pattern = f"({pattern}|{uncommit_pattern})"
+ output += self.read_until_pattern(pattern=new_pattern)
+ # Do not save 'uncommited changes'
+ if uncommit_pattern in output:
+ self.write_channel(self.normalize_cmd("no"))
+ output += self.read_until_pattern(pattern=pattern)
+
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
+
+ def save_config(
+ self, cmd: str = "commit", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
+ """Saves Config"""
+ raise NotImplementedError
def exit_config_mode(self, exit_config: str = "end", pattern: str = r"#") -> str:
+ """
+ Exit from configuration mode.
+
+ Viptela might have the following in the output (if no 'commit()' occurred.
+
+ Uncommitted changes found, commit them? [yes/no/CANCEL]
+ """
+ output = ""
+ if self.check_config_mode():
+ 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 not re.search(pattern, output, flags=re.M):
+ uncommit_pattern = r"Uncommitted changes found"
+ new_pattern = f"({pattern}|{uncommit_pattern})"
+ output += self.read_until_pattern(pattern=new_pattern)
+ # Do not save 'uncommited changes'
+ if uncommit_pattern in output:
+ self.write_channel(self.normalize_cmd("no"))
+ output += self.read_until_pattern(pattern=pattern)
+
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
Prepare the session after the connection has been established.
+
+Source code
+
def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.disable_paging(command="paginate false")
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/netmiko/cisco/cisco_wlc_ssh.html b/docs/netmiko/cisco/cisco_wlc_ssh.html
index 4a0973d99..8016ec807 100644
--- a/docs/netmiko/cisco/cisco_wlc_ssh.html
+++ b/docs/netmiko/cisco/cisco_wlc_ssh.html
@@ -24,24 +24,25 @@
Module netmiko.cisco.cisco_wlc_ssh
Source code
"""Netmiko Cisco WLC support."""
+from typing import Any, Union, Sequence, TextIO
import time
import re
import socket
-from netmiko.ssh_exception import NetmikoAuthenticationException
+from netmiko.exceptions import NetmikoAuthenticationException
from netmiko.base_connection import BaseConnection
class CiscoWlcSSH(BaseConnection):
"""Netmiko Cisco WLC support."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
# WLC/AireOS has an issue where you can get "No Existing Session" with
# the default conn_timeout (so increase conn_timeout to 10-seconds).
kwargs.setdefault("conn_timeout", 10)
return super().__init__(*args, **kwargs)
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""WLC presents with the following on login (in certain OS versions)
login as: user
@@ -60,17 +61,19 @@
Module netmiko.cisco.cisco_wlc_ssh
output = self.read_channel()
if output:
if "login as" in output or "User:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
else:
- self.write_channel(self.RETURN)
+ # no output read, sleep and go for one more round of read channel
time.sleep(delay_factor * 1.5)
i += 1
- def send_command_w_enter(self, *args, **kwargs):
+ def send_command_w_enter(self, *args: Any, **kwargs: Any) -> str:
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
@@ -84,7 +87,7 @@
Module netmiko.cisco.cisco_wlc_ssh
# If no delay_factor use 1 for default value
delay_factor = kwargs.get("delay_factor", 1)
kwargs["delay_factor"] = self.select_delay_factor(delay_factor)
- output = self.send_command_timing(*args, **kwargs)
+ output = self._send_command_timing_str(*args, **kwargs)
if "Press any key" in output or "Press Enter to" in output:
new_args = list(args)
@@ -96,7 +99,7 @@
Module netmiko.cisco.cisco_wlc_ssh
kwargs["max_loops"] = 150
# Send an 'enter'
- output = self.send_command_timing(*new_args, **kwargs)
+ output += self._send_command_timing_str(*new_args, **kwargs)
# WLC has excessive delay after this appears on screen
if "802.11b Advanced Configuration" in output:
@@ -122,13 +125,30 @@
Module netmiko.cisco.cisco_wlc_ssh
output = self.strip_prompt(output)
return output
- def session_preparation(self):
+ def send_command_w_yes(self, *args: Any, **kwargs: Any) -> str:
+ """
+ For 'show interface summary' Cisco WLC adds a
+ 'Would you like to display the next 15 entries?' message
+ Even though pagination is disabled
+ Arguments are the same as send_command_timing() method
+ """
+ output = self._send_command_timing_str(*args, **kwargs)
+ if "(y/n)" in output:
+ output += self._send_command_timing_str("y")
+ strip_prompt = kwargs.get("strip_prompt", True)
+ if strip_prompt:
+ # Had to strip trailing prompt twice.
+ output = self.strip_prompt(output)
+ output = self.strip_prompt(output)
+ return output
+
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
Cisco WLC uses "config paging disable" to disable paging
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
try:
self.set_base_prompt()
@@ -137,11 +157,8 @@
Module netmiko.cisco.cisco_wlc_ssh
raise NetmikoAuthenticationException(msg)
self.disable_paging(command="config paging disable")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Reset WLC back to normal paging and gracefully close session."""
self.send_command_timing("config paging enable")
@@ -177,31 +194,33 @@
**kwargs,
)
- def save_config(self, cmd="save config", confirm=True, confirm_response="y"):
+ def save_config(
+ self,
+ cmd: str = "save config",
+ confirm: bool = True,
+ confirm_response: str = "y",
+ ) -> str:
"""Saves Config."""
self.enable()
if confirm:
- output = self.send_command_timing(command_string=cmd)
+ output = self._send_command_timing_str(command_string=cmd)
if confirm_response:
- output += self.send_command_timing(confirm_response)
+ output += self._send_command_timing_str(confirm_response)
else:
# Send enter by default
- output += self.send_command_timing(self.RETURN)
+ output += self._send_command_timing_str(self.RETURN)
else:
# Some devices are slow so match on trailing-prompt if you can
- output = self.send_command(command_string=cmd)
+ output = self._send_command_str(command_string=cmd)
return output
@@ -244,144 +268,117 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoWlcSSH(BaseConnection):
"""Netmiko Cisco WLC support."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
# WLC/AireOS has an issue where you can get "No Existing Session" with
# the default conn_timeout (so increase conn_timeout to 10-seconds).
kwargs.setdefault("conn_timeout", 10)
return super().__init__(*args, **kwargs)
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""WLC presents with the following on login (in certain OS versions)
login as: user
@@ -400,17 +397,19 @@
Classes
output = self.read_channel()
if output:
if "login as" in output or "User:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
else:
- self.write_channel(self.RETURN)
+ # no output read, sleep and go for one more round of read channel
time.sleep(delay_factor * 1.5)
i += 1
- def send_command_w_enter(self, *args, **kwargs):
+ def send_command_w_enter(self, *args: Any, **kwargs: Any) -> str:
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
@@ -424,7 +423,7 @@
Classes
# If no delay_factor use 1 for default value
delay_factor = kwargs.get("delay_factor", 1)
kwargs["delay_factor"] = self.select_delay_factor(delay_factor)
- output = self.send_command_timing(*args, **kwargs)
+ output = self._send_command_timing_str(*args, **kwargs)
if "Press any key" in output or "Press Enter to" in output:
new_args = list(args)
@@ -436,7 +435,7 @@
Classes
kwargs["max_loops"] = 150
# Send an 'enter'
- output = self.send_command_timing(*new_args, **kwargs)
+ output += self._send_command_timing_str(*new_args, **kwargs)
# WLC has excessive delay after this appears on screen
if "802.11b Advanced Configuration" in output:
@@ -462,13 +461,30 @@
Classes
output = self.strip_prompt(output)
return output
- def session_preparation(self):
+ def send_command_w_yes(self, *args: Any, **kwargs: Any) -> str:
+ """
+ For 'show interface summary' Cisco WLC adds a
+ 'Would you like to display the next 15 entries?' message
+ Even though pagination is disabled
+ Arguments are the same as send_command_timing() method
+ """
+ output = self._send_command_timing_str(*args, **kwargs)
+ if "(y/n)" in output:
+ output += self._send_command_timing_str("y")
+ strip_prompt = kwargs.get("strip_prompt", True)
+ if strip_prompt:
+ # Had to strip trailing prompt twice.
+ output = self.strip_prompt(output)
+ output = self.strip_prompt(output)
+ return output
+
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
Cisco WLC uses "config paging disable" to disable paging
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
try:
self.set_base_prompt()
@@ -477,11 +493,8 @@
Classes
raise NetmikoAuthenticationException(msg)
self.disable_paging(command="config paging disable")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Reset WLC back to normal paging and gracefully close session."""
self.send_command_timing("config paging enable")
@@ -517,31 +530,33 @@
def check_config_mode(
+ self, check_string: str = "config", pattern: str = ""
+) -> bool:
"""Checks if the device is in configuration mode or not."""
if not pattern:
pattern = re.escape(self.base_prompt)
@@ -591,7 +613,7 @@
Methods
Reset WLC back to normal paging and gracefully close session.
Source code
-
def cleanup(self, command="logout"):
+
def cleanup(self, command: str = "logout") -> None:
"""Reset WLC back to normal paging and gracefully close session."""
self.send_command_timing("config paging enable")
@@ -629,17 +651,19 @@
def send_command_w_enter(self, *args: Any, **kwargs: Any) -> str:
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
@@ -704,7 +731,7 @@
Methods
# If no delay_factor use 1 for default value
delay_factor = kwargs.get("delay_factor", 1)
kwargs["delay_factor"] = self.select_delay_factor(delay_factor)
- output = self.send_command_timing(*args, **kwargs)
+ output = self._send_command_timing_str(*args, **kwargs)
if "Press any key" in output or "Press Enter to" in output:
new_args = list(args)
@@ -716,7 +743,7 @@
Methods
kwargs["max_loops"] = 150
# Send an 'enter'
- output = self.send_command_timing(*new_args, **kwargs)
+ output += self._send_command_timing_str(*new_args, **kwargs)
# WLC has excessive delay after this appears on screen
if "802.11b Advanced Configuration" in output:
@@ -743,6 +770,34 @@
Methods
return output
+
+def send_command_w_yes(self, *args, **kwargs)
+
+
+
For 'show interface summary' Cisco WLC adds a
+'Would you like to display the next 15 entries?' message
+Even though pagination is disabled
+Arguments are the same as send_command_timing() method
+
+Source code
+
def send_command_w_yes(self, *args: Any, **kwargs: Any) -> str:
+ """
+ For 'show interface summary' Cisco WLC adds a
+ 'Would you like to display the next 15 entries?' message
+ Even though pagination is disabled
+ Arguments are the same as send_command_timing() method
+ """
+ output = self._send_command_timing_str(*args, **kwargs)
+ if "(y/n)" in output:
+ output += self._send_command_timing_str("y")
+ strip_prompt = kwargs.get("strip_prompt", True)
+ if strip_prompt:
+ # Had to strip trailing prompt twice.
+ output = self.strip_prompt(output)
+ output = self.strip_prompt(output)
+ return output
+
+
def session_preparation(self)
@@ -751,13 +806,13 @@
Methods
Cisco WLC uses "config paging disable" to disable paging
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
Cisco WLC uses "config paging disable" to disable paging
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
try:
self.set_base_prompt()
@@ -765,14 +820,11 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""WLC presents with the following on login (in certain OS versions)
login as: user
@@ -801,13 +853,15 @@
Methods
output = self.read_channel()
if output:
if "login as" in output or "User:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
else:
- self.write_channel(self.RETURN)
+ # no output read, sleep and go for one more round of read channel
time.sleep(delay_factor * 1.5)
i += 1
from typing import Optional, Any, Union, Sequence, TextIO
+import re
+import warnings
+from netmiko.base_connection import DELAY_FACTOR_DEPR_SIMPLE_MSG
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):
+ def establish_connection(self, width: int = 511, height: int = 511) -> None:
"""Establish SSH connection to the network device"""
- super().establish_connection(width=511, height=511)
+ super().establish_connection(width=width, height=height)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# IOS-XR has an issue where it echoes the command even though it hasn't returned the prompt
self._test_channel_read(pattern=r"[>#]")
@@ -47,15 +44,26 @@
comment:
command_string = commit comment <comment>
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
supported combinations
label and confirm:
command_string = commit label <label> confirmed <confirm_delay>
@@ -89,7 +99,8 @@
Module netmiko.cisco.cisco_xr
Exit of configuration mode with pending changes will cause the changes to be discarded and
an exception to be generated.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm and not confirm_delay:
raise ValueError("Invalid arguments supplied to XR commit")
if confirm_delay and not confirm:
@@ -120,24 +131,40 @@
Module netmiko.cisco.cisco_xr
# Enter config mode (if necessary)
output = self.config_mode()
- output += self.send_command_expect(
+
+ # IOS-XR might do this:
+ # This could be a few minutes if your config is large. Confirm? [y/n][confirm]
+ new_data = self._send_command_str(
command_string,
+ expect_string=r"(#|onfirm)",
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
+ if "onfirm" in new_data:
+ output += new_data
+ new_data = self._send_command_str(
+ "y",
+ expect_string=r"#",
+ strip_prompt=False,
+ strip_command=False,
+ read_timeout=read_timeout,
+ )
+ output += new_data
if error_marker in output:
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
if alt_error_marker in output:
# Other commits occurred, don't proceed with commit
- output += self.send_command_timing(
- "no", strip_prompt=False, strip_command=False, delay_factor=delay_factor
+ output += self._send_command_timing_str(
+ "no", strip_prompt=False, strip_command=False
)
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
return output
- def check_config_mode(self, check_string=")#", pattern=r"[#\$]"):
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[#\$]"
+ ) -> bool:
"""Checks if the device is in configuration mode or not.
IOS-XR, unfortunately, does this:
@@ -150,7 +177,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
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):
+ def establish_connection(self, width: int = 511, height: int = 511) -> None:
"""Establish SSH connection to the network device"""
- super().establish_connection(width=511, height=511)
+ super().establish_connection(width=width, height=height)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# IOS-XR has an issue where it echoes the command even though it hasn't returned the prompt
self._test_channel_read(pattern=r"[>#]")
@@ -398,15 +395,26 @@
comment:
command_string = commit comment <comment>
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
supported combinations
label and confirm:
command_string = commit label <label> confirmed <confirm_delay>
@@ -440,7 +450,8 @@
Classes
Exit of configuration mode with pending changes will cause the changes to be discarded and
an exception to be generated.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm and not confirm_delay:
raise ValueError("Invalid arguments supplied to XR commit")
if confirm_delay and not confirm:
@@ -471,24 +482,40 @@
Classes
# Enter config mode (if necessary)
output = self.config_mode()
- output += self.send_command_expect(
+
+ # IOS-XR might do this:
+ # This could be a few minutes if your config is large. Confirm? [y/n][confirm]
+ new_data = self._send_command_str(
command_string,
+ expect_string=r"(#|onfirm)",
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
+ if "onfirm" in new_data:
+ output += new_data
+ new_data = self._send_command_str(
+ "y",
+ expect_string=r"#",
+ strip_prompt=False,
+ strip_command=False,
+ read_timeout=read_timeout,
+ )
+ output += new_data
if error_marker in output:
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
if alt_error_marker in output:
# Other commits occurred, don't proceed with commit
- output += self.send_command_timing(
- "no", strip_prompt=False, strip_command=False, delay_factor=delay_factor
+ output += self._send_command_timing_str(
+ "no", strip_prompt=False, strip_command=False
)
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
return output
- def check_config_mode(self, check_string=")#", pattern=r"[#\$]"):
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[#\$]"
+ ) -> bool:
"""Checks if the device is in configuration mode or not.
IOS-XR, unfortunately, does this:
@@ -501,7 +528,7 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# IOS-XR has an issue where it echoes the command even though it hasn't returned the prompt
self._test_channel_read(pattern=r"[>#]")
@@ -772,8 +830,7 @@
def remote_md5(
+ self, base_cmd: str = "show md5 file", remote_file: Optional[str] = None
+) -> str:
"""
IOS-XR for MD5 requires this extra leading /
@@ -909,7 +976,7 @@
show md5 file /bootflash:/boot/g
remote_file = self.source_file
# IOS-XR requires both the leading slash and the slash between file-system and file here
remote_md5_cmd = f"{base_cmd} /{self.file_system}/{remote_file}"
- dest_md5 = self.ssh_ctl_chan.send_command(remote_md5_cmd, max_loops=1500)
+ dest_md5 = self.ssh_ctl_chan._send_command_str(remote_md5_cmd, read_timeout=300)
dest_md5 = self.process_md5(dest_md5)
return dest_md5
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoAsaSSH(CiscoSSHConnection):
"""Subclass specific to Cisco ASA."""
- def __init__(self, *args, **kwargs):
- kwargs.setdefault("fast_cli", True)
- kwargs.setdefault("_legacy_mode", False)
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
kwargs.setdefault("allow_auto_change", True)
return super().__init__(*args, **kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# Make sure the ASA is ready
@@ -323,21 +302,25 @@
Inherited members
self.set_base_prompt()
- def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[>\#]"
+ ) -> bool:
return super().check_config_mode(check_string=check_string, pattern=pattern)
def enable(
self,
- cmd="enable",
- pattern="ssword",
- enable_pattern=r"\#",
- re_flags=re.IGNORECASE,
- ):
+ cmd: str = "enable",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = r"\#",
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
return super().enable(
cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
)
- def send_command_timing(self, *args, **kwargs):
+ def send_command_timing(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -351,7 +334,9 @@
Inherited members
self.set_base_prompt()
return output
- def send_command(self, *args, **kwargs):
+ def send_command(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -373,11 +358,7 @@
Inherited members
return output
- def send_command_expect(self, *args, **kwargs):
- """Backwards compaitibility."""
- return self.send_command(*args, **kwargs)
-
- def set_base_prompt(self, *args, **kwargs):
+ def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Cisco ASA in multi-context mode needs to have the base prompt updated
(if you switch contexts i.e. 'changeto')
@@ -391,8 +372,10 @@
def send_command(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -555,18 +548,6 @@
def send_command_timing(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
@@ -597,7 +580,7 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
# Make sure the ASA is ready
@@ -636,7 +619,7 @@
Methods
happens the trailing '(config*' needs stripped off.
Source code
-
def set_base_prompt(self, *args, **kwargs):
+
def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Cisco ASA in multi-context mode needs to have the base prompt updated
(if you switch contexts i.e. 'changeto')
@@ -649,7 +632,9 @@
Methods
if match:
# strip off (conf.* from base_prompt
self.base_prompt = match.group(1)
- return self.base_prompt
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CiscoFtdSSH(CiscoSSHConnection):
+
class CiscoFtdSSH(NoEnable, NoConfig, CiscoSSHConnection):
"""Subclass specific to Cisco FTD."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- def send_config_set(self, *args, **kwargs):
+ def send_config_set(self, *args: Any, **kwargs: Any) -> str:
"""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"""
+ def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
+ """Canot change config on FTD via ssh"""
return False
def send_config_set(self, *args: Any, **kwargs: Any) -> str:
"""Canot change config on FTD via ssh"""
raise NotImplementedError
@@ -920,9 +849,9 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoIosBase(CiscoBaseConnection):
"""Common Methods for IOS (both SSH and telnet)."""
- def __init__(self, *args, **kwargs):
- # Cisco-IOS 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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
cmd = "terminal width 511"
self.set_terminal_width(command=cmd, pattern=cmd)
self.disable_paging()
self.set_base_prompt()
- def check_config_mode(self, check_string=")#", pattern="#"):
+ def check_config_mode(self, check_string: str = ")#", pattern: str = r"#") -> bool:
"""
Checks if the device is in configuration mode or not.
@@ -1133,7 +1031,9 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
cmd = "terminal width 511"
self.set_terminal_width(command=cmd, pattern=cmd)
@@ -1192,9 +1094,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
# NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
@@ -2179,46 +1981,45 @@
Inherited members
self.disable_paging()
self.set_base_prompt()
- def normalize_linefeeds(self, a_string):
+ def normalize_linefeeds(self, a_string: str) -> str:
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n\r|\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
return newline.sub(self.RESPONSE_RETURN, a_string).replace("\r", "\n")
- def check_config_mode(self, check_string=")#", pattern="#"):
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string, pattern=pattern)
def save_config(
self,
- cmd="copy running-config startup-config",
- confirm=False,
- confirm_response="",
- ):
+ cmd: str = "copy running-config startup-config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
self.enable()
+ output = ""
if confirm:
- output = self.send_command_timing(
+ output += self._send_command_timing_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
if confirm_response:
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
confirm_response, strip_prompt=False, strip_command=False
)
else:
# Send enter by default
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
self.RETURN, strip_prompt=False, strip_command=False
)
else:
# NX-OS is very slow on save_config ensure it waits long enough.
- # FIX: this is a hack as delay_factor will be set to .1 via fast_cli=True in
- # send_command so increase max_loops.
- output = self.send_command(
+ output += self._send_command_str(
command_string=cmd,
strip_prompt=False,
strip_command=False,
- max_loops=5000,
+ read_timeout=100,
)
return output
@@ -2237,7 +2038,7 @@
Methods
Checks if the device is in configuration mode or not.
def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string, pattern=pattern)
@@ -2253,7 +2054,7 @@
Methods
's in the text.
Source code
-
def normalize_linefeeds(self, a_string):
+
def normalize_linefeeds(self, a_string: str) -> str:
"""Convert '\r\n' or '\r\r\n' to '\n, and remove extra '\r's in the text."""
newline = re.compile(r"(\r\r\n\r|\r\r\n|\r\n)")
# NX-OS fix for incorrect MD5 on 9K (due to strange <enter> patterns on NX-OS)
@@ -2267,7 +2068,7 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
# NX-OS has an issue where it echoes the command even though it hasn't returned the prompt
@@ -2287,9 +2088,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CiscoS300SSH(CiscoSSHConnection):
- """
- Support for Cisco SG300 series of devices.
-
- Note, must configure the following to disable SG300 from prompting for username twice:
-
- configure terminal
- ip ssh password-auth
- """
-
- def session_preparation(self):
- """Prepare the session after the connection has been established."""
- self.ansi_escape_codes = True
- self._test_channel_read()
- self.set_base_prompt()
- self.set_terminal_width(command="terminal width 511", pattern="terminal")
- self.disable_paging(command="terminal datadump")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
-
- def save_config(self, cmd="write memory", confirm=True, confirm_response="Y"):
- return super().save_config(
- cmd=cmd, confirm=confirm, confirm_response=confirm_response
- )
Support for Cisco SG300 series of devices, with telnet.
+Note: can be used with Sx200 series, with telnet enabled.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CiscoTpTcCeSSH(CiscoSSHConnection):
- def __init__(self, *args, **kwargs):
- default_enter = kwargs.get("default_enter")
- kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
- super().__init__(*args, **kwargs)
-
- def disable_paging(self, *args, **kwargs):
- """Paging is disabled by default."""
- return ""
-
- def session_preparation(self):
- """
- Prepare the session after the connection has been established
-
- This method handles some of vagaries that occur between various devices
- early on in the session.
-
- In general, it should include:
- self.set_base_prompt()
- self.disable_paging()
- self.set_terminal_width()
- """
- self._test_channel_read()
- self.set_base_prompt()
- self.set_terminal_width()
- self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def set_base_prompt(self, *args, **kwargs):
- """Use 'OK' as base_prompt."""
- self.base_prompt = "OK"
- return self.base_prompt
-
- def find_prompt(self, *args, **kwargs):
- """Use 'OK' as standard prompt."""
- return "OK"
-
- def strip_prompt(self, a_string):
- """Strip the trailing router prompt from the output."""
- expect_string = r"^(OK|ERROR|Command not recognized\.)$"
- response_list = a_string.split(self.RESPONSE_RETURN)
- last_line = response_list[-1]
- if re.search(expect_string, last_line):
- return self.RESPONSE_RETURN.join(response_list[:-1])
- else:
- return a_string
-
- def send_command(self, *args, **kwargs):
- """
- Send command to network device retrieve output until router_prompt or expect_string
-
- By default this method will keep waiting to receive data until the network device prompt is
- detected. The current network device prompt will be determined automatically.
- """
- if len(args) >= 2:
- expect_string = args[1]
- else:
- expect_string = kwargs.get("expect_string")
- if expect_string is None:
- expect_string = r"(OK|ERROR|Command not recognized\.)"
- expect_string = self.RETURN + expect_string + self.RETURN
- kwargs.setdefault("expect_string", expect_string)
-
- output = super().send_command(*args, **kwargs)
- return output
+
class CiscoS300Telnet(CiscoS300Base):
+ """
+ Support for Cisco SG300 series of devices, with telnet.
+ Note: can be used with Sx200 series, with telnet enabled.
+ """
- def save_config(self, *args, **kwargs):
- """Not Implemented"""
- raise NotImplementedError
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
+
+Source code
+
class CiscoTpTcCeSSH(CiscoSSHConnection):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ default_enter = kwargs.get("default_enter")
+ kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
+ super().__init__(*args, **kwargs)
+
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
+ """Paging is disabled by default."""
+ return ""
+
+ def session_preparation(self) -> None:
+ """
+ Prepare the session after the connection has been established
+
+ This method handles some of vagaries that occur between various devices
+ early on in the session.
+
+ In general, it should include:
+ self.set_base_prompt()
+ self.disable_paging()
+ self.set_terminal_width()
+ """
+ # Could not work out what the CLI looked like. It would be good to switch to
+ # a pattern on the _test_channel_read() call.
+ self._test_channel_read()
+ self.set_base_prompt()
+ self.set_terminal_width()
+ self.disable_paging()
+ # Clear the read buffer
+ time.sleep(0.3 * self.global_delay_factor)
+ self.clear_buffer()
+
+ def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
+ """Use 'OK' as base_prompt."""
+ self.base_prompt = "OK"
+ return self.base_prompt
+
+ def find_prompt(self, *args: Any, **kwargs: Any) -> str:
+ """Use 'OK' as standard prompt."""
+ return "OK"
+
+ def strip_prompt(self, a_string: str) -> str:
+ """Strip the trailing router prompt from the output."""
+ expect_string = r"^(OK|ERROR|Command not recognized\.)$"
+ response_list = a_string.split(self.RESPONSE_RETURN)
+ last_line = response_list[-1]
+ if re.search(expect_string, last_line):
+ return self.RESPONSE_RETURN.join(response_list[:-1])
+ else:
+ return a_string
+
+ def send_command(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """
+ Send command to network device retrieve output until router_prompt or expect_string
+
+ By default this method will keep waiting to receive data until the network device prompt is
+ detected. The current network device prompt will be determined automatically.
+ """
+ if len(args) >= 2:
+ expect_string = args[1]
+ else:
+ expect_string = kwargs.get("expect_string")
+ if expect_string is None:
+ expect_string = r"(OK|ERROR|Command not recognized\.)"
+ expect_string = self.RETURN + expect_string + self.RETURN
+ kwargs.setdefault("expect_string", expect_string)
+
+ output = super().send_command(*args, **kwargs)
+ return output
+
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
+ """Not Implemented"""
+ raise NotImplementedError
detected. The current network device prompt will be determined automatically.
Source code
-
def send_command(self, *args, **kwargs):
+
def send_command(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""
Send command to network device retrieve output until router_prompt or expect_string
@@ -2863,7 +2751,7 @@
Methods
self.set_terminal_width()
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -2875,6 +2763,8 @@
Methods
self.disable_paging()
self.set_terminal_width()
"""
+ # Could not work out what the CLI looked like. It would be good to switch to
+ # a pattern on the _test_channel_read() call.
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
@@ -2891,7 +2781,7 @@
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
+
+Source code
+
class CiscoViptelaSSH(CiscoSSHConnection):
+ """Subclass specific to Cisco Viptela."""
+
+ def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.disable_paging(command="paginate false")
+
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
+ """Checks if the device is in configuration mode or not."""
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
+
+ def commit(self, confirm: bool = False, confirm_response: str = "") -> str:
+ cmd = "commit"
+ return super().save_config(
+ cmd=cmd, confirm=confirm, confirm_response=confirm_response
+ )
+
+ def config_mode(
+ self,
+ config_command: str = "conf terminal",
+ pattern: str = "",
+ re_flags: int = 0,
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
+
+ def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = False,
+ **kwargs: Any,
+ ) -> str:
+ return super().send_config_set(
+ config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ )
+
+ def exit_config_mode(self, exit_config: str = "end", pattern: str = r"#") -> str:
+ """
+ Exit from configuration mode.
+
+ Viptela might have the following in the output (if no 'commit()' occurred.
+
+ Uncommitted changes found, commit them? [yes/no/CANCEL]
+ """
+ output = ""
+ if self.check_config_mode():
+ 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 not re.search(pattern, output, flags=re.M):
+ uncommit_pattern = r"Uncommitted changes found"
+ new_pattern = f"({pattern}|{uncommit_pattern})"
+ output += self.read_until_pattern(pattern=new_pattern)
+ # Do not save 'uncommited changes'
+ if uncommit_pattern in output:
+ self.write_channel(self.normalize_cmd("no"))
+ output += self.read_until_pattern(pattern=pattern)
+
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
+
+ def save_config(
+ self, cmd: str = "commit", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
+ """Saves Config"""
+ raise NotImplementedError
def exit_config_mode(self, exit_config: str = "end", pattern: str = r"#") -> str:
+ """
+ Exit from configuration mode.
+
+ Viptela might have the following in the output (if no 'commit()' occurred.
+
+ Uncommitted changes found, commit them? [yes/no/CANCEL]
+ """
+ output = ""
+ if self.check_config_mode():
+ 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 not re.search(pattern, output, flags=re.M):
+ uncommit_pattern = r"Uncommitted changes found"
+ new_pattern = f"({pattern}|{uncommit_pattern})"
+ output += self.read_until_pattern(pattern=new_pattern)
+ # Do not save 'uncommited changes'
+ if uncommit_pattern in output:
+ self.write_channel(self.normalize_cmd("no"))
+ output += self.read_until_pattern(pattern=pattern)
+
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
Prepare the session after the connection has been established.
+
+Source code
+
def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.disable_paging(command="paginate false")
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class CiscoWlcSSH(BaseConnection):
"""Netmiko Cisco WLC support."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
# WLC/AireOS has an issue where you can get "No Existing Session" with
# the default conn_timeout (so increase conn_timeout to 10-seconds).
kwargs.setdefault("conn_timeout", 10)
return super().__init__(*args, **kwargs)
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""WLC presents with the following on login (in certain OS versions)
login as: user
@@ -3124,17 +3305,19 @@
Inherited members
output = self.read_channel()
if output:
if "login as" in output or "User:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
else:
- self.write_channel(self.RETURN)
+ # no output read, sleep and go for one more round of read channel
time.sleep(delay_factor * 1.5)
i += 1
- def send_command_w_enter(self, *args, **kwargs):
+ def send_command_w_enter(self, *args: Any, **kwargs: Any) -> str:
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
@@ -3148,7 +3331,7 @@
Inherited members
# If no delay_factor use 1 for default value
delay_factor = kwargs.get("delay_factor", 1)
kwargs["delay_factor"] = self.select_delay_factor(delay_factor)
- output = self.send_command_timing(*args, **kwargs)
+ output = self._send_command_timing_str(*args, **kwargs)
if "Press any key" in output or "Press Enter to" in output:
new_args = list(args)
@@ -3160,7 +3343,7 @@
Inherited members
kwargs["max_loops"] = 150
# Send an 'enter'
- output = self.send_command_timing(*new_args, **kwargs)
+ output += self._send_command_timing_str(*new_args, **kwargs)
# WLC has excessive delay after this appears on screen
if "802.11b Advanced Configuration" in output:
@@ -3186,13 +3369,30 @@
Inherited members
output = self.strip_prompt(output)
return output
- def session_preparation(self):
+ def send_command_w_yes(self, *args: Any, **kwargs: Any) -> str:
+ """
+ For 'show interface summary' Cisco WLC adds a
+ 'Would you like to display the next 15 entries?' message
+ Even though pagination is disabled
+ Arguments are the same as send_command_timing() method
+ """
+ output = self._send_command_timing_str(*args, **kwargs)
+ if "(y/n)" in output:
+ output += self._send_command_timing_str("y")
+ strip_prompt = kwargs.get("strip_prompt", True)
+ if strip_prompt:
+ # Had to strip trailing prompt twice.
+ output = self.strip_prompt(output)
+ output = self.strip_prompt(output)
+ return output
+
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
Cisco WLC uses "config paging disable" to disable paging
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
try:
self.set_base_prompt()
@@ -3201,11 +3401,8 @@
Inherited members
raise NetmikoAuthenticationException(msg)
self.disable_paging(command="config paging disable")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Reset WLC back to normal paging and gracefully close session."""
self.send_command_timing("config paging enable")
@@ -3241,31 +3438,33 @@
def check_config_mode(
+ self, check_string: str = "config", pattern: str = ""
+) -> bool:
"""Checks if the device is in configuration mode or not."""
if not pattern:
pattern = re.escape(self.base_prompt)
@@ -3315,7 +3521,7 @@
Methods
Reset WLC back to normal paging and gracefully close session.
Source code
-
def cleanup(self, command="logout"):
+
def cleanup(self, command: str = "logout") -> None:
"""Reset WLC back to normal paging and gracefully close session."""
self.send_command_timing("config paging enable")
@@ -3353,17 +3559,19 @@
def send_command_w_enter(self, *args: Any, **kwargs: Any) -> str:
"""
For 'show run-config' Cisco WLC adds a 'Press Enter to continue...' message
Even though pagination is disabled
@@ -3428,7 +3639,7 @@
Methods
# If no delay_factor use 1 for default value
delay_factor = kwargs.get("delay_factor", 1)
kwargs["delay_factor"] = self.select_delay_factor(delay_factor)
- output = self.send_command_timing(*args, **kwargs)
+ output = self._send_command_timing_str(*args, **kwargs)
if "Press any key" in output or "Press Enter to" in output:
new_args = list(args)
@@ -3440,7 +3651,7 @@
Methods
kwargs["max_loops"] = 150
# Send an 'enter'
- output = self.send_command_timing(*new_args, **kwargs)
+ output += self._send_command_timing_str(*new_args, **kwargs)
# WLC has excessive delay after this appears on screen
if "802.11b Advanced Configuration" in output:
@@ -3467,6 +3678,34 @@
Methods
return output
+
+def send_command_w_yes(self, *args, **kwargs)
+
+
+
For 'show interface summary' Cisco WLC adds a
+'Would you like to display the next 15 entries?' message
+Even though pagination is disabled
+Arguments are the same as send_command_timing() method
+
+Source code
+
def send_command_w_yes(self, *args: Any, **kwargs: Any) -> str:
+ """
+ For 'show interface summary' Cisco WLC adds a
+ 'Would you like to display the next 15 entries?' message
+ Even though pagination is disabled
+ Arguments are the same as send_command_timing() method
+ """
+ output = self._send_command_timing_str(*args, **kwargs)
+ if "(y/n)" in output:
+ output += self._send_command_timing_str("y")
+ strip_prompt = kwargs.get("strip_prompt", True)
+ if strip_prompt:
+ # Had to strip trailing prompt twice.
+ output = self.strip_prompt(output)
+ output = self.strip_prompt(output)
+ return output
+
+
def session_preparation(self)
@@ -3475,13 +3714,13 @@
Methods
Cisco WLC uses "config paging disable" to disable paging
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
Cisco WLC uses "config paging disable" to disable paging
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
try:
self.set_base_prompt()
@@ -3489,14 +3728,11 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""WLC presents with the following on login (in certain OS versions)
login as: user
@@ -3525,13 +3761,15 @@
Methods
output = self.read_channel()
if output:
if "login as" in output or "User:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
else:
- self.write_channel(self.RETURN)
+ # no output read, sleep and go for one more round of read channel
time.sleep(delay_factor * 1.5)
i += 1
def remote_md5(
+ self, base_cmd: str = "show md5 file", remote_file: Optional[str] = None
+) -> str:
"""
IOS-XR for MD5 requires this extra leading /
@@ -3681,7 +3928,7 @@
show md5 file /bootflash:/boot/g
remote_file = self.source_file
# IOS-XR requires both the leading slash and the slash between file-system and file here
remote_md5_cmd = f"{base_cmd} /{self.file_system}/{remote_file}"
- dest_md5 = self.ssh_ctl_chan.send_command(remote_md5_cmd, max_loops=1500)
+ dest_md5 = self.ssh_ctl_chan._send_command_str(remote_md5_cmd, read_timeout=300)
dest_md5 = self.process_md5(dest_md5)
return dest_md5
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
self.socket_timeout = socket_timeout
@staticmethod
- def _read_file(file_name):
+ def _read_file(file_name: str) -> str:
with io.open(file_name, "rt", encoding="utf-8") as f:
return f.read()
@staticmethod
- def _tcl_newline_rationalize(tcl_string):
+ def _tcl_newline_rationalize(tcl_string: str) -> str:
r"""
When using put inside a TCL {} section the newline is considered a new TCL
statement and causes a missing curly-brace message. Convert "\n" to "\r". TCL
@@ -4186,17 +4386,22 @@
def telnet_login(
self,
- pri_prompt_terminator=r"\#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
+ pri_prompt_terminator: str = r"\#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
"""Telnet login. Can be username/password or just password."""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -144,6 +142,7 @@
Module netmiko.cisco_base_connection
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -171,9 +170,12 @@
Module netmiko.cisco_base_connection
# Check for device with no password configured
if re.search(r"assword required, but none set", output):
+ assert self.remote_conn is not None
self.remote_conn.close()
- msg = "Login failed - Password required, but none set: {}".format(
- self.host
+ msg = (
+ "Login failed - Password required, but none set: {}".format(
+ self.host
+ )
)
raise NetmikoAuthenticationException(msg)
@@ -186,6 +188,7 @@
Module netmiko.cisco_base_connection
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -205,11 +208,12 @@
Module netmiko.cisco_base_connection
):
return return_msg
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -218,20 +222,23 @@
Module netmiko.cisco_base_connection
except Exception:
pass
# Always try to send final 'exit' (command)
- self._session_log_fin = True
+ if self.session_log:
+ self.session_log.fin = True
self.write_channel(command + self.RETURN)
- def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"):
+ def _autodetect_fs(
+ self, cmd: str = "dir", pattern: str = r"Directory of (.*)/"
+ ) -> str:
"""Autodetect the file system on the remote device. Used by SCP operations."""
if not self.check_enable_mode():
raise ValueError("Must be in enable mode to auto-detect the file-system.")
- output = self.send_command_expect(cmd)
+ output = self._send_command_str(cmd)
match = re.search(pattern, output)
if match:
file_system = match.group(1)
# Test file_system
cmd = f"dir {file_system}"
- output = self.send_command_expect(cmd)
+ output = self._send_command_str(cmd)
if "% Invalid" in output or "%Error:" in output:
raise ValueError(
"An error occurred in dynamically determining remote file "
@@ -247,28 +254,28 @@
Module netmiko.cisco_base_connection
def save_config(
self,
- cmd="copy running-config startup-config",
- confirm=False,
- confirm_response="",
- ):
+ cmd: str = "copy running-config startup-config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Saves Config."""
self.enable()
if confirm:
- output = self.send_command_timing(
+ output = self._send_command_timing_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
if confirm_response:
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
confirm_response, strip_prompt=False, strip_command=False
)
else:
# Send enter by default
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
self.RETURN, strip_prompt=False, strip_command=False
)
else:
# Some devices are slow so match on trailing-prompt if you can
- output = self.send_command(
+ output = self._send_command_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
return output
@@ -293,7 +300,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
def telnet_login(
self,
- pri_prompt_terminator=r"\#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
+ pri_prompt_terminator: str = r"\#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
"""Telnet login. Can be username/password or just password."""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -542,6 +519,7 @@
Classes
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -569,9 +547,12 @@
Classes
# Check for device with no password configured
if re.search(r"assword required, but none set", output):
+ assert self.remote_conn is not None
self.remote_conn.close()
- msg = "Login failed - Password required, but none set: {}".format(
- self.host
+ msg = (
+ "Login failed - Password required, but none set: {}".format(
+ self.host
+ )
)
raise NetmikoAuthenticationException(msg)
@@ -584,6 +565,7 @@
Classes
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -603,11 +585,12 @@
Classes
):
return return_msg
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -616,20 +599,23 @@
Classes
except Exception:
pass
# Always try to send final 'exit' (command)
- self._session_log_fin = True
+ if self.session_log:
+ self.session_log.fin = True
self.write_channel(command + self.RETURN)
- def _autodetect_fs(self, cmd="dir", pattern=r"Directory of (.*)/"):
+ def _autodetect_fs(
+ self, cmd: str = "dir", pattern: str = r"Directory of (.*)/"
+ ) -> str:
"""Autodetect the file system on the remote device. Used by SCP operations."""
if not self.check_enable_mode():
raise ValueError("Must be in enable mode to auto-detect the file-system.")
- output = self.send_command_expect(cmd)
+ output = self._send_command_str(cmd)
match = re.search(pattern, output)
if match:
file_system = match.group(1)
# Test file_system
cmd = f"dir {file_system}"
- output = self.send_command_expect(cmd)
+ output = self._send_command_str(cmd)
if "% Invalid" in output or "%Error:" in output:
raise ValueError(
"An error occurred in dynamically determining remote file "
@@ -645,28 +631,28 @@
Classes
def save_config(
self,
- cmd="copy running-config startup-config",
- confirm=False,
- confirm_response="",
- ):
+ cmd: str = "copy running-config startup-config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Saves Config."""
self.enable()
if confirm:
- output = self.send_command_timing(
+ output = self._send_command_timing_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
if confirm_response:
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
confirm_response, strip_prompt=False, strip_command=False
)
else:
# Send enter by default
- output += self.send_command_timing(
+ output += self._send_command_timing_str(
self.RETURN, strip_prompt=False, strip_command=False
)
else:
# Some devices are slow so match on trailing-prompt if you can
- output = self.send_command(
+ output = self._send_command_str(
command_string=cmd, strip_prompt=False, strip_command=False
)
return output
@@ -705,7 +691,7 @@
Methods
Cisco IOS devices abbreviate the prompt at 20 chars in config mode
Telnet login. Can be username/password or just password.
@@ -889,17 +855,16 @@
Methods
Source code
def telnet_login(
self,
- pri_prompt_terminator=r"\#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
-):
+ pri_prompt_terminator: str = r"\#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+) -> str:
"""Telnet login. Can be username/password or just password."""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -928,6 +893,7 @@
Methods
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -955,9 +921,12 @@
Methods
# Check for device with no password configured
if re.search(r"assword required, but none set", output):
+ assert self.remote_conn is not None
self.remote_conn.close()
- msg = "Login failed - Password required, but none set: {}".format(
- self.host
+ msg = (
+ "Login failed - Password required, but none set: {}".format(
+ self.host
+ )
)
raise NetmikoAuthenticationException(msg)
@@ -970,6 +939,7 @@
Methods
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -989,6 +959,7 @@
Methods
):
return return_msg
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class NetscalerSSH(BaseConnection):
- """ Netscaler SSH class. """
+
class NetscalerSSH(NoConfig, BaseConnection):
+ """Netscaler SSH class."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- # 0 will defer to the global delay factor
- delay_factor = self.select_delay_factor(delay_factor=0)
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
cmd = f"{self.RETURN}set cli mode -page OFF{self.RETURN}"
self.disable_paging(command=cmd)
- time.sleep(1 * delay_factor)
self.set_base_prompt()
- time.sleep(0.3 * delay_factor)
- self.clear_buffer()
def set_base_prompt(
- self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt.
- Netscaler has '>' for the prompt.
+ Netscaler has only '>' for the prompt.
"""
- prompt = self.find_prompt(delay_factor=delay_factor)
- if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
- raise ValueError(f"Router prompt not found: {repr(prompt)}")
-
- prompt = prompt.strip()
- if len(prompt) == 1:
- self.base_prompt = prompt
- else:
- # Strip off trailing terminator
- self.base_prompt = prompt[:-1]
+ base_prompt = super().set_base_prompt(
+ pri_prompt_terminator=pri_prompt_terminator,
+ alt_prompt_terminator=alt_prompt_terminator,
+ delay_factor=delay_factor,
+ pattern=pattern,
+ )
+ # If null-string, set base_prompt to just ">"
+ if not base_prompt:
+ self.base_prompt = pri_prompt_terminator
return self.base_prompt
- def check_config_mode(self):
- """Netscaler devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Netscaler devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Netscaler devices do not have a config mode."""
- return ""
-
- def strip_prompt(self, a_string):
- """ Strip 'Done' from command output """
+ def strip_prompt(self, a_string: str) -> str:
+ """Strip 'Done' from command output"""
output = super().strip_prompt(a_string)
lines = output.split(self.RESPONSE_RETURN)
if "Done" in lines[-1]:
@@ -239,46 +198,11 @@
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class NetscalerSSH(BaseConnection):
- """ Netscaler SSH class. """
+
class NetscalerSSH(NoConfig, BaseConnection):
+ """Netscaler SSH class."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- # 0 will defer to the global delay factor
- delay_factor = self.select_delay_factor(delay_factor=0)
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
cmd = f"{self.RETURN}set cli mode -page OFF{self.RETURN}"
self.disable_paging(command=cmd)
- time.sleep(1 * delay_factor)
self.set_base_prompt()
- time.sleep(0.3 * delay_factor)
- self.clear_buffer()
def set_base_prompt(
- self, pri_prompt_terminator="#", alt_prompt_terminator=">", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt.
- Netscaler has '>' for the prompt.
+ Netscaler has only '>' for the prompt.
"""
- prompt = self.find_prompt(delay_factor=delay_factor)
- if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
- raise ValueError(f"Router prompt not found: {repr(prompt)}")
-
- prompt = prompt.strip()
- if len(prompt) == 1:
- self.base_prompt = prompt
- else:
- # Strip off trailing terminator
- self.base_prompt = prompt[:-1]
+ base_prompt = super().set_base_prompt(
+ pri_prompt_terminator=pri_prompt_terminator,
+ alt_prompt_terminator=alt_prompt_terminator,
+ delay_factor=delay_factor,
+ pattern=pattern,
+ )
+ # If null-string, set base_prompt to just ">"
+ if not base_prompt:
+ self.base_prompt = pri_prompt_terminator
return self.base_prompt
- def check_config_mode(self):
- """Netscaler devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Netscaler devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Netscaler devices do not have a config mode."""
- return ""
-
- def strip_prompt(self, a_string):
- """ Strip 'Done' from command output """
+ def strip_prompt(self, a_string: str) -> str:
+ """Strip 'Done' from command output"""
output = super().strip_prompt(a_string)
lines = output.split(self.RESPONSE_RETURN)
if "Done" in lines[-1]:
@@ -289,46 +234,11 @@
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CloudGenixIonSSH(CiscoSSHConnection):
- def establish_connection(self):
- super().establish_connection(width=100, height=1000)
+
class CloudGenixIonSSH(NoConfig, CiscoSSHConnection):
+ def establish_connection(self, width: int = 100, height: int = 1000) -> None:
+ super().establish_connection(width=width, height=height)
- def session_preparation(self, *args, **kwargs):
+ def session_preparation(self, *args: Any, **kwargs: Any) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.write_channel(self.RETURN)
self.set_base_prompt(delay_factor=5)
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""Cloud Genix ION sets terminal height in establish_connection"""
return ""
- def find_prompt(self, delay_factor=1):
- prompt = super().find_prompt(delay_factor=delay_factor)
+ def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+ ) -> str:
+ prompt = super().find_prompt(delay_factor=delay_factor, pattern=pattern)
prompt = self.strip_backspaces(prompt).strip()
return prompt
- def strip_command(self, command_string, output):
+ def strip_command(self, command_string: str, output: str) -> str:
output = super().strip_command(command_string, output)
# command_string gets repainted potentially multiple times (grab everything after last one)
output = output.split(command_string)[-1]
return output
- def check_config_mode(self):
- """Devices do not have a config mode."""
- return False
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
+ """Not Implemented"""
+ raise NotImplementedError
- def config_mode(self):
- """Devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Devices do not have a config mode."""
- return ""
-
- def save_config(self, *args, **kwargs):
- """No save method on ION SSH"""
- pass
-
- def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
+ def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = False,
+ **kwargs: Any
+ ) -> str:
return super().send_config_set(
config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
)
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CloudGenixIonSSH(CiscoSSHConnection):
- def establish_connection(self):
- super().establish_connection(width=100, height=1000)
+
class CloudGenixIonSSH(NoConfig, CiscoSSHConnection):
+ def establish_connection(self, width: int = 100, height: int = 1000) -> None:
+ super().establish_connection(width=width, height=height)
- def session_preparation(self, *args, **kwargs):
+ def session_preparation(self, *args: Any, **kwargs: Any) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.write_channel(self.RETURN)
self.set_base_prompt(delay_factor=5)
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""Cloud Genix ION sets terminal height in establish_connection"""
return ""
- def find_prompt(self, delay_factor=1):
- prompt = super().find_prompt(delay_factor=delay_factor)
+ def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+ ) -> str:
+ prompt = super().find_prompt(delay_factor=delay_factor, pattern=pattern)
prompt = self.strip_backspaces(prompt).strip()
return prompt
- def strip_command(self, command_string, output):
+ def strip_command(self, command_string: str, output: str) -> str:
output = super().strip_command(command_string, output)
# command_string gets repainted potentially multiple times (grab everything after last one)
output = output.split(command_string)[-1]
return output
- def check_config_mode(self):
- """Devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Devices do not have a config mode."""
- return ""
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
+ """Not Implemented"""
+ raise NotImplementedError
- def save_config(self, *args, **kwargs):
- """No save method on ION SSH"""
- pass
-
- def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
+ def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = False,
+ **kwargs: Any
+ ) -> str:
return super().send_config_set(
config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
)
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CoriantSSH(CiscoSSHConnection):
- def session_preparation(self):
- self._test_channel_read()
+
class CoriantSSH(NoEnable, NoConfig, CiscoSSHConnection):
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[>:]")
self.set_base_prompt()
- def check_enable_mode(self, *args, **kwargs):
- raise AttributeError("Coriant devices do not support enable mode!")
-
- def enable(self, *args, **kwargs):
- raise AttributeError("Coriant devices do not support enable mode!")
-
- def exit_enable_mode(self, *args, **kwargs):
- raise AttributeError("Coriant devices do not support enable mode!")
-
- def check_config_mode(self):
- """Coriant devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Coriant devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Coriant devices do not have a config mode."""
- return ""
-
def set_base_prompt(
- self, pri_prompt_terminator=":", alt_prompt_terminator=">", delay_factor=2
- ):
+ self,
+ pri_prompt_terminator: str = ":",
+ alt_prompt_terminator: str = ">",
+ delay_factor: float = 2.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
return self.base_prompt
- def save_config(self, *args, **kwargs):
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
"""Not Implemented"""
raise NotImplementedError
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class CoriantSSH(CiscoSSHConnection):
- def session_preparation(self):
- self._test_channel_read()
+
class CoriantSSH(NoEnable, NoConfig, CiscoSSHConnection):
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[>:]")
self.set_base_prompt()
- def check_enable_mode(self, *args, **kwargs):
- raise AttributeError("Coriant devices do not support enable mode!")
-
- def enable(self, *args, **kwargs):
- raise AttributeError("Coriant devices do not support enable mode!")
-
- def exit_enable_mode(self, *args, **kwargs):
- raise AttributeError("Coriant devices do not support enable mode!")
-
- def check_config_mode(self):
- """Coriant devices do not have a config mode."""
- return False
-
- def config_mode(self):
- """Coriant devices do not have a config mode."""
- return ""
-
- def exit_config_mode(self):
- """Coriant devices do not have a config mode."""
- return ""
-
def set_base_prompt(
- self, pri_prompt_terminator=":", alt_prompt_terminator=">", delay_factor=2
- ):
+ self,
+ pri_prompt_terminator: str = ":",
+ alt_prompt_terminator: str = ">",
+ delay_factor: float = 2.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
return self.base_prompt
- def save_config(self, *args, **kwargs):
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
"""Not Implemented"""
raise NotImplementedError
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
"""Dell PowerConnect Driver."""
+from typing import Optional
from paramiko import SSHClient
import time
from os import path
+from netmiko.ssh_auth import SSHClient_noauth
from netmiko.cisco_base_connection import CiscoBaseConnection
-class SSHClient_noauth(SSHClient):
- def _auth(self, username, *args):
- self._transport.auth_none(username)
- return
-
-
class DellPowerConnectBase(CiscoBaseConnection):
"""Dell PowerConnect Driver."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
self.disable_paging(command="terminal datadump")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
def set_base_prompt(
- self, pri_prompt_terminator=">", alt_prompt_terminator="#", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
prompt = super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
prompt = prompt.strip()
self.base_prompt = prompt
return self.base_prompt
- def check_config_mode(self, check_string="(config)#"):
+ def check_config_mode(
+ self, check_string: str = "(config)#", pattern: str = ""
+ ) -> bool:
"""Checks if the device is in configuration mode"""
- return super().check_config_mode(check_string=check_string)
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
- def config_mode(self, config_command="config"):
- """Enter configuration mode."""
- return super().config_mode(config_command=config_command)
+ def config_mode(
+ self, config_command: str = "config", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
class DellPowerConnectSSH(DellPowerConnectBase):
@@ -79,13 +82,14 @@
Module netmiko.dell.dell_powerconnect
If we use login/password, the ssh server use the (none) auth mechanism.
"""
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection.
See base_connection.py file for any updates.
"""
# Create instance of SSHClient object
# If user does not provide SSH key, we use noauth
+ remote_conn_pre: SSHClient
if not self.use_keys:
remote_conn_pre = SSHClient_noauth()
else:
@@ -101,7 +105,7 @@
Module netmiko.dell.dell_powerconnect
remote_conn_pre.set_missing_host_key_policy(self.key_policy)
return remote_conn_pre
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Powerconnect presents with the following on login
@@ -117,8 +121,10 @@
Module netmiko.dell.dell_powerconnect
output = self.read_channel()
if output:
if "User Name:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -145,7 +151,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class DellPowerConnectBase(CiscoBaseConnection):
"""Dell PowerConnect Driver."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.enable()
self.disable_paging(command="terminal datadump")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
def set_base_prompt(
- self, pri_prompt_terminator=">", alt_prompt_terminator="#", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
prompt = super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
prompt = prompt.strip()
self.base_prompt = prompt
return self.base_prompt
- def check_config_mode(self, check_string="(config)#"):
+ def check_config_mode(
+ self, check_string: str = "(config)#", pattern: str = ""
+ ) -> bool:
"""Checks if the device is in configuration mode"""
- return super().check_config_mode(check_string=check_string)
-
- def config_mode(self, config_command="config"):
- """Enter configuration mode."""
- return super().config_mode(config_command=config_command)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -586,13 +538,14 @@
Inherited members
If we use login/password, the ssh server use the (none) auth mechanism.
"""
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection.
See base_connection.py file for any updates.
"""
# Create instance of SSHClient object
# If user does not provide SSH key, we use noauth
+ remote_conn_pre: SSHClient
if not self.use_keys:
remote_conn_pre = SSHClient_noauth()
else:
@@ -608,7 +561,7 @@
Inherited members
remote_conn_pre.set_missing_host_key_policy(self.key_policy)
return remote_conn_pre
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Powerconnect presents with the following on login
@@ -624,8 +577,10 @@
Inherited members
output = self.read_channel()
if output:
if "User Name:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -643,7 +598,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
A high-level representation of a session with an SSH server.
-This class
-wraps .Transport, .Channel, and .SFTPClient to take care of most
-aspects of authenticating and opening channels.
-A typical use case is::
You may pass in explicit overrides for authentication and server host key
-checking.
-The default mechanism is to try to use local key files or an
-SSH agent (if one is running).
-
Instances of this class may be used as context managers.
Dell EMC PowerSwitch platforms running Enterprise SONiC Distribution
+by Dell Technologies Driver - supports dellenterprisesonic.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
+
+Source code
+
class DellSonicSSH(NoEnable, CiscoSSHConnection):
+ """
+ Dell EMC PowerSwitch platforms running Enterprise SONiC Distribution
+ by Dell Technologies Driver - supports dellenterprisesonic.
+ """
+
+ def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>$#]")
+ self._enter_shell()
+ self.disable_paging()
+ self.set_base_prompt(alt_prompt_terminator="$")
+
+ def config_mode(
+ self,
+ config_command: str = "configure terminal",
+ pattern: str = r"\#",
+ re_flags: int = 0,
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
+
+ def _enter_shell(self) -> str:
+ """Enter the sonic-cli Shell."""
+ log.debug("Enter sonic-cli Shell.")
+ return self._send_command_str("sonic-cli", expect_string=r"\#")
+
+ def _return_cli(self) -> str:
+ """Return to the CLI."""
+ return self._send_command_str("exit", expect_string=r"\$")
Prepare the session after the connection has been established.
+
+Source code
+
def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>$#]")
+ self._enter_shell()
+ self.disable_paging()
+ self.set_base_prompt(alt_prompt_terminator="$")
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -1652,13 +1468,14 @@
Inherited members
If we use login/password, the ssh server use the (none) auth mechanism.
"""
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Prepare for Paramiko SSH connection.
See base_connection.py file for any updates.
"""
# Create instance of SSHClient object
# If user does not provide SSH key, we use noauth
+ remote_conn_pre: SSHClient
if not self.use_keys:
remote_conn_pre = SSHClient_noauth()
else:
@@ -1674,7 +1491,7 @@
Inherited members
remote_conn_pre.set_missing_host_key_policy(self.key_policy)
return remote_conn_pre
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Powerconnect presents with the following on login
@@ -1690,8 +1507,10 @@
Inherited members
output = self.read_channel()
if output:
if "User Name:" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -1709,7 +1528,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Dell EMC PowerSwitch platforms running Enterprise SONiC Distribution
+by Dell Technologies Driver - supports dellenterprisesonic.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
+
+Source code
+
class DellSonicSSH(NoEnable, CiscoSSHConnection):
+ """
+ Dell EMC PowerSwitch platforms running Enterprise SONiC Distribution
+ by Dell Technologies Driver - supports dellenterprisesonic.
+ """
+
+ def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>$#]")
+ self._enter_shell()
+ self.disable_paging()
+ self.set_base_prompt(alt_prompt_terminator="$")
+
+ def config_mode(
+ self,
+ config_command: str = "configure terminal",
+ pattern: str = r"\#",
+ re_flags: int = 0,
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
+
+ def _enter_shell(self) -> str:
+ """Enter the sonic-cli Shell."""
+ log.debug("Enter sonic-cli Shell.")
+ return self._send_command_str("sonic-cli", expect_string=r"\#")
+
+ def _return_cli(self) -> str:
+ """Return to the CLI."""
+ return self._send_command_str("exit", expect_string=r"\$")
Prepare the session after the connection has been established.
+
+Source code
+
def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>$#]")
+ self._enter_shell()
+ self.disable_paging()
+ self.set_base_prompt(alt_prompt_terminator="$")
Supports D-Link DGS/DES device series (there are some DGS/DES devices that are web-only)
@@ -108,187 +82,134 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Supports D-Link DGS/DES device series (there are some DGS/DES devices that are web-only)
@@ -468,131 +322,104 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class DlinkDSTelnet(DlinkDSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
Supports D-Link DGS/DES device series (there are some DGS/DES devices that are web-only)
@@ -53,131 +53,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class DlinkDSTelnet(DlinkDSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class EltexSSH(CiscoSSHConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.disable_paging(command="terminal datadump")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def save_config(self, *args, **kwargs):
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
"""Not Implemented"""
raise NotImplementedError
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class EltexSSH(CiscoSSHConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.disable_paging(command="terminal datadump")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def save_config(self, *args, **kwargs):
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
"""Not Implemented"""
raise NotImplementedError
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Automatically enters configuration mode
- """
-
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -153,11 +156,11 @@
Module netmiko.ericsson.ericsson_ipos
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -179,7 +182,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class EricssonIposSSH(BaseConnection):
- def check_enable_mode(self, check_string="#"):
- """
- Check if in enable mode. Return boolean.
- """
- return super().check_enable_mode(check_string=check_string)
-
- def enable(self, cmd="enable 15", pattern="ssword", re_flags=re.IGNORECASE):
- """Enter enable mode."""
- return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
-
- def disable_paging(self, command="terminal length 0", delay_factor=1):
- """Disable paging default to a Cisco CLI method.
-
- :param command: Device command to disable pagination of output
- :type command: str
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.set_terminal_width(command="terminal width 512", pattern=r"terminal")
+ self.disable_paging()
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
- """
- return super().disable_paging(command=command, delay_factor=delay_factor)
-
- def set_terminal_width(self, command="terminal width 512", delay_factor=1):
- """CLI terminals try to automatically adjust the line based on the width of the terminal.
- This causes the output to get distorted when accessed programmatically.
-
- Set terminal width to 511 which works on a broad set of devices.
-
- :param command: Command string to send to the device
- :type command: str
-
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
- """
- return super().set_terminal_width(command=command, delay_factor=delay_factor)
+ def check_enable_mode(self, check_string: str = "#") -> bool:
+ return super().check_enable_mode(check_string=check_string)
- def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
- """Ericsson IPOS requires you not exit from configuration mode."""
- return super().send_config_set(
- config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ def enable(
+ self,
+ cmd: str = "enable 15",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
+ return super().enable(
+ cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
)
- def exit_enable_mode(self, exit_command="disable"):
- """
- Exits enable (privileged exec) mode.
- """
+ def exit_enable_mode(self, exit_command: str = "disable") -> str:
return super().exit_enable_mode(exit_command=exit_command)
- def check_config_mode(self, check_string=")#", pattern=""):
- """
- Checks if the device is in configuration mode or not.
- """
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
return super().check_config_mode(check_string=check_string, pattern=pattern)
- def config_mode(self, config_command="configure", pattern=""):
- """
- Enter into configuration mode on remote device.
- """
- if not pattern:
- pattern = re.escape(self.base_prompt[:16])
- return super().config_mode(config_command=config_command, pattern=pattern)
+ def config_mode(
+ self, config_command: str = "configure", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
- def exit_config_mode(self, exit_config="end", pattern="#"):
+ def exit_config_mode(self, exit_config: str = "end", pattern: str = "#") -> str:
"""
Exit from configuration mode.
Ercisson output :
@@ -386,28 +334,52 @@
Automatically enters configuration mode
- """
-
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -442,11 +415,11 @@
Classes
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -462,45 +435,25 @@
Checks if the device is in configuration mode or not.
-
-Source code
-
def check_config_mode(self, check_string=")#", pattern=""):
- """
- Checks if the device is in configuration mode or not.
- """
- return super().check_config_mode(check_string=check_string, pattern=pattern)
-
-
-
-def check_enable_mode(self, check_string='#')
-
-
-
Check if in enable mode. Return boolean.
-
-Source code
-
def check_enable_mode(self, check_string="#"):
- """
- Check if in enable mode. Return boolean.
- """
- return super().check_enable_mode(check_string=check_string)
Automatically enters configuration mode
- """
-
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -535,11 +489,11 @@
Methods
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -550,34 +504,6 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class EricssonIposSSH(BaseConnection):
- def check_enable_mode(self, check_string="#"):
- """
- Check if in enable mode. Return boolean.
- """
- return super().check_enable_mode(check_string=check_string)
-
- def enable(self, cmd="enable 15", pattern="ssword", re_flags=re.IGNORECASE):
- """Enter enable mode."""
- return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
-
- def disable_paging(self, command="terminal length 0", delay_factor=1):
- """Disable paging default to a Cisco CLI method.
-
- :param command: Device command to disable pagination of output
- :type command: str
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.set_terminal_width(command="terminal width 512", pattern=r"terminal")
+ self.disable_paging()
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
- """
- return super().disable_paging(command=command, delay_factor=delay_factor)
-
- def set_terminal_width(self, command="terminal width 512", delay_factor=1):
- """CLI terminals try to automatically adjust the line based on the width of the terminal.
- This causes the output to get distorted when accessed programmatically.
-
- Set terminal width to 511 which works on a broad set of devices.
-
- :param command: Command string to send to the device
- :type command: str
-
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
- """
- return super().set_terminal_width(command=command, delay_factor=delay_factor)
+ def check_enable_mode(self, check_string: str = "#") -> bool:
+ return super().check_enable_mode(check_string=check_string)
- def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
- """Ericsson IPOS requires you not exit from configuration mode."""
- return super().send_config_set(
- config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ def enable(
+ self,
+ cmd: str = "enable 15",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
+ return super().enable(
+ cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
)
- def exit_enable_mode(self, exit_command="disable"):
- """
- Exits enable (privileged exec) mode.
- """
+ def exit_enable_mode(self, exit_command: str = "disable") -> str:
return super().exit_enable_mode(exit_command=exit_command)
- def check_config_mode(self, check_string=")#", pattern=""):
- """
- Checks if the device is in configuration mode or not.
- """
+ def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
return super().check_config_mode(check_string=check_string, pattern=pattern)
- def config_mode(self, config_command="configure", pattern=""):
- """
- Enter into configuration mode on remote device.
- """
- if not pattern:
- pattern = re.escape(self.base_prompt[:16])
- return super().config_mode(config_command=config_command, pattern=pattern)
+ def config_mode(
+ self, config_command: str = "configure", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
- def exit_config_mode(self, exit_config="end", pattern="#"):
+ def exit_config_mode(self, exit_config: str = "end", pattern: str = "#") -> str:
"""
Exit from configuration mode.
Ercisson output :
@@ -252,28 +197,52 @@
Automatically enters configuration mode
- """
-
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -308,11 +278,11 @@
Classes
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -328,45 +298,25 @@
Checks if the device is in configuration mode or not.
-
-Source code
-
def check_config_mode(self, check_string=")#", pattern=""):
- """
- Checks if the device is in configuration mode or not.
- """
- return super().check_config_mode(check_string=check_string, pattern=pattern)
-
-
-
-def check_enable_mode(self, check_string='#')
-
-
-
Check if in enable mode. Return boolean.
-
-Source code
-
def check_enable_mode(self, check_string="#"):
- """
- Check if in enable mode. Return boolean.
- """
- return super().check_enable_mode(check_string=check_string)
Automatically enters configuration mode
- """
-
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -401,11 +352,11 @@
Methods
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -416,34 +367,6 @@
SSH authentication exception based on Paramiko AuthenticationException.
+
+Source code
+
class NetmikoAuthenticationException(AuthenticationException):
+ """SSH authentication exception based on Paramiko AuthenticationException."""
+
+ pass
SSH authentication exception based on Paramiko AuthenticationException.
+
+Source code
+
class NetmikoAuthenticationException(AuthenticationException):
+ """SSH authentication exception based on Paramiko AuthenticationException."""
+
+ pass
+
+
Ancestors
+
+
paramiko.ssh_exception.AuthenticationException
+
paramiko.ssh_exception.SSHException
+
builtins.Exception
+
builtins.BaseException
+
+
+
+class NetmikoBaseException
+(*args, **kwargs)
+
+
+
General base exception except for exceptions that inherit from Paramiko.
+
+Source code
+
class NetmikoBaseException(Exception):
+ """General base exception except for exceptions that inherit from Paramiko."""
+
+ pass
Netmiko support for Extreme Ethernet Routing Switch.
@@ -87,138 +100,117 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeErsSSH(CiscoSSHConnection):
"""Netmiko support for Extreme Ethernet Routing Switch."""
- def special_login_handler(self, delay_factor=1):
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.set_terminal_width()
+ self.disable_paging()
+
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Extreme ERS presents the following as part of the login process:
@@ -235,8 +227,10 @@
Classes
if "Ctrl-Y" in output:
self.write_channel(CTRL_Y)
if "sername" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "ssword" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(0.5 * delay_factor)
@@ -245,7 +239,12 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Extreme ERS presents the following as part of the login process:
@@ -298,8 +302,10 @@
Methods
if "Ctrl-Y" in output:
self.write_channel(CTRL_Y)
if "sername" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "ssword" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(0.5 * delay_factor)
@@ -318,9 +324,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class ExtremeExosBase(CiscoSSHConnection):
+
class ExtremeExosBase(NoConfig, CiscoSSHConnection):
"""Extreme Exos support.
Designed for EXOS >= 15.0
"""
- def session_preparation(self):
- self._test_channel_read()
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"#")
self.set_base_prompt()
self.disable_paging(command="disable clipaging")
self.send_command_timing("disable cli prompting")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def set_base_prompt(self, *args, **kwargs):
+ def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Extreme attaches an id to the prompt. The id increases with every command.
It needs to br stripped off to match the prompt. Eg.
@@ -297,7 +400,9 @@
Classes
else:
return self.base_prompt
- def send_command(self, *args, **kwargs):
+ def send_command(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Extreme needs special handler here due to the prompt changes."""
# Change send_command behavior to use self.base_prompt
@@ -307,21 +412,12 @@
Extreme needs special handler here due to the prompt changes.
Source code
-
def send_command(self, *args, **kwargs):
+
def send_command(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
"""Extreme needs special handler here due to the prompt changes."""
# Change send_command behavior to use self.base_prompt
@@ -427,7 +493,7 @@
Methods
Source code
-
def set_base_prompt(self, *args, **kwargs):
+
def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""
Extreme attaches an id to the prompt. The id increases with every command.
It needs to br stripped off to match the prompt. Eg.
@@ -457,23 +523,25 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeExosTelnet(ExtremeExosBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeNetironBase(CiscoSSHConnection):
- def save_config(self, cmd="write memory", confirm=False, confirm_response=""):
- """Save Config"""
- return super().save_config(
- cmd=cmd, confirm=confirm, confirm_response=confirm_response
- )
-
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self.disable_paging(command="skip-page-display")
self.set_terminal_width()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeNetironTelnet(ExtremeNetironBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- self.disable_paging(command="terminal more disable")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="terminal more disable")
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeWingSSH(CiscoSSHConnection):
"""Extreme WiNG support."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Disable paging and set Max term width"""
self._test_channel_read(pattern=r">|#")
self.set_base_prompt()
self.set_terminal_width(command="terminal width 512", pattern="terminal")
- self.disable_paging(command="no page")
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="no page")
Ancestors
@@ -213,14 +181,12 @@
Methods
Disable paging and set Max term width
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Disable paging and set Max term width"""
self._test_channel_read(pattern=r">|#")
self.set_base_prompt()
self.set_terminal_width(command="terminal width 512", pattern="terminal")
- self.disable_paging(command="no page")
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
Netmiko support for Extreme Ethernet Routing Switch.
@@ -95,138 +102,117 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeErsSSH(CiscoSSHConnection):
"""Netmiko support for Extreme Ethernet Routing Switch."""
- def special_login_handler(self, delay_factor=1):
+ def session_preparation(self) -> None:
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.set_terminal_width()
+ self.disable_paging()
+
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Extreme ERS presents the following as part of the login process:
@@ -243,8 +229,10 @@
Classes
if "Ctrl-Y" in output:
self.write_channel(CTRL_Y)
if "sername" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "ssword" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(0.5 * delay_factor)
@@ -253,7 +241,12 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Extreme ERS presents the following as part of the login process:
@@ -306,8 +304,10 @@
Methods
if "Ctrl-Y" in output:
self.write_channel(CTRL_Y)
if "sername" in output:
+ assert isinstance(self.username, str)
self.write_channel(self.username + self.RETURN)
elif "ssword" in output:
+ assert isinstance(self.password, str)
self.write_channel(self.password + self.RETURN)
break
time.sleep(0.5 * delay_factor)
@@ -326,9 +326,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeExosTelnet(ExtremeExosBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeNetironTelnet(ExtremeNetironBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
- self.disable_paging(command="terminal more disable")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="terminal more disable")
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ExtremeWingSSH(CiscoSSHConnection):
"""Extreme WiNG support."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Disable paging and set Max term width"""
self._test_channel_read(pattern=r">|#")
self.set_base_prompt()
self.set_terminal_width(command="terminal width 512", pattern="terminal")
- self.disable_paging(command="no page")
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+ self.disable_paging(command="no page")
Ancestors
@@ -2123,14 +2291,12 @@
Methods
Disable paging and set Max term width
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Disable paging and set Max term width"""
self._test_channel_read(pattern=r">|#")
self.set_base_prompt()
self.set_terminal_width(command="terminal width 512", pattern="terminal")
- self.disable_paging(command="no page")
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class F5TmshSSH(BaseConnection):
- def session_preparation(self):
+
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class F5TmshSSH(BaseConnection):
- def session_preparation(self):
+
check:
command_string = commit check
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
@@ -170,19 +169,19 @@
Module netmiko.flexvnf.flexvnf_ssh
# and_quit will get out of config mode on commit
if and_quit:
prompt = self.base_prompt
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
expect_string=prompt,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
else:
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -190,12 +189,12 @@
Module netmiko.flexvnf.flexvnf_ssh
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip the trailing router prompt from the output."""
a_string = super().strip_prompt(*args, **kwargs)
- return self.strip_context_items(a_string)
+ return self._strip_context_items(a_string)
- def strip_context_items(self, a_string):
+ def _strip_context_items(self, a_string: str) -> str:
"""Strip FLEXVNF-specific output.
FLEXVNF will also put a configuration context:
@@ -239,161 +238,137 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class FlexvnfSSH(BaseConnection):
- def session_preparation(self):
+
class FlexvnfSSH(NoEnable, BaseConnection):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Disable paging (the '--more--' prompts).
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[\$@>%]")
self.enter_cli_mode()
self.set_base_prompt()
self.set_terminal_width(command="set screen width 511", pattern="set")
self.disable_paging(command="set screen length 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def enter_cli_mode(self):
+ def enter_cli_mode(self) -> None:
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
@@ -403,7 +378,7 @@
check:
command_string = commit check
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
@@ -518,19 +492,19 @@
Classes
# and_quit will get out of config mode on commit
if and_quit:
prompt = self.base_prompt
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
expect_string=prompt,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
else:
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -538,12 +512,12 @@
Classes
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip the trailing router prompt from the output."""
a_string = super().strip_prompt(*args, **kwargs)
- return self.strip_context_items(a_string)
+ return self._strip_context_items(a_string)
- def strip_context_items(self, a_string):
+ def _strip_context_items(self, a_string: str) -> str:
"""Strip FLEXVNF-specific output.
FLEXVNF will also put a configuration context:
@@ -577,36 +551,25 @@
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string="]"):
+
def check_config_mode(self, check_string: str = "]", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string)
check:
command_string = commit check
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
@@ -696,19 +665,19 @@
Methods
# and_quit will get out of config mode on commit
if and_quit:
prompt = self.base_prompt
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
expect_string=prompt,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
else:
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -718,27 +687,19 @@
def enter_cli_mode(self) -> None:
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
@@ -758,7 +719,7 @@
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Disable paging (the '--more--' prompts).
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[\$@>%]")
self.enter_cli_mode()
self.set_base_prompt()
self.set_terminal_width(command="set screen width 511", pattern="set")
- self.disable_paging(command="set screen length 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
-
-
-def strip_context_items(self, a_string)
-
-
-
Strip FLEXVNF-specific output.
-
FLEXVNF will also put a configuration context:
-[edit]
-
and various chassis contexts:
-{master:0}, {backup:1}
-
This method removes those lines.
-
-Source code
-
def strip_context_items(self, a_string):
- """Strip FLEXVNF-specific output.
-
- FLEXVNF will also put a configuration context:
- [edit]
-
- and various chassis contexts:
- {master:0}, {backup:1}
-
- This method removes those lines.
- """
- strings_to_strip = [
- r"admin@lab-pg-dev-cp02v.*",
- r"\[edit.*\]",
- r"\[edit\]",
- r"\[ok\]",
- r"\[.*\]",
- r"\{master:.*\}",
- r"\{backup:.*\}",
- r"\{line.*\}",
- r"\{primary.*\}",
- r"\{secondary.*\}",
- ]
-
- response_list = a_string.split(self.RESPONSE_RETURN)
- last_line = response_list[0]
-
- for pattern in strings_to_strip:
- if re.search(pattern, last_line):
- return self.RESPONSE_RETURN.join(response_list[:-1])
- return a_string
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class FlexvnfSSH(BaseConnection):
- def session_preparation(self):
+
class FlexvnfSSH(NoEnable, BaseConnection):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Disable paging (the '--more--' prompts).
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[\$@>%]")
self.enter_cli_mode()
self.set_base_prompt()
self.set_terminal_width(command="set screen width 511", pattern="set")
self.disable_paging(command="set screen length 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def enter_cli_mode(self):
+ def enter_cli_mode(self) -> None:
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
@@ -209,7 +185,7 @@
check:
command_string = commit check
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
@@ -324,19 +299,19 @@
Classes
# and_quit will get out of config mode on commit
if and_quit:
prompt = self.base_prompt
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
expect_string=prompt,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
else:
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -344,12 +319,12 @@
Classes
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip the trailing router prompt from the output."""
a_string = super().strip_prompt(*args, **kwargs)
- return self.strip_context_items(a_string)
+ return self._strip_context_items(a_string)
- def strip_context_items(self, a_string):
+ def _strip_context_items(self, a_string: str) -> str:
"""Strip FLEXVNF-specific output.
FLEXVNF will also put a configuration context:
@@ -383,36 +358,25 @@
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string="]"):
+
def check_config_mode(self, check_string: str = "]", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string)
check:
command_string = commit check
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
@@ -502,19 +472,19 @@
Methods
# and_quit will get out of config mode on commit
if and_quit:
prompt = self.base_prompt
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
expect_string=prompt,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
else:
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=True,
strip_command=True,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
if commit_marker not in output:
@@ -524,27 +494,19 @@
def enter_cli_mode(self) -> None:
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
@@ -564,7 +526,7 @@
Set the base prompt for interaction ('>').
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
Disable paging (the '--more--' prompts).
Set the base prompt for interaction ('>').
"""
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[\$@>%]")
self.enter_cli_mode()
self.set_base_prompt()
self.set_terminal_width(command="set screen width 511", pattern="set")
- self.disable_paging(command="set screen length 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
-
-
-def strip_context_items(self, a_string)
-
-
-
Strip FLEXVNF-specific output.
-
FLEXVNF will also put a configuration context:
-[edit]
-
and various chassis contexts:
-{master:0}, {backup:1}
-
This method removes those lines.
-
-Source code
-
def strip_context_items(self, a_string):
- """Strip FLEXVNF-specific output.
-
- FLEXVNF will also put a configuration context:
- [edit]
-
- and various chassis contexts:
- {master:0}, {backup:1}
-
- This method removes those lines.
- """
- strings_to_strip = [
- r"admin@lab-pg-dev-cp02v.*",
- r"\[edit.*\]",
- r"\[edit\]",
- r"\[ok\]",
- r"\[.*\]",
- r"\{master:.*\}",
- r"\{backup:.*\}",
- r"\{line.*\}",
- r"\{primary.*\}",
- r"\{secondary.*\}",
- ]
-
- response_list = a_string.split(self.RESPONSE_RETURN)
- last_line = response_list[0]
-
- for pattern in strings_to_strip:
- if re.search(pattern, last_line):
- return self.RESPONSE_RETURN.join(response_list[:-1])
- return a_string
import paramiko
-import time
import re
+from typing import Optional
+
+from netmiko.no_config import NoConfig
from netmiko.cisco_base_connection import CiscoSSHConnection
-class FortinetSSH(CiscoSSHConnection):
- def _modify_connection_params(self):
+class FortinetSSH(NoConfig, CiscoSSHConnection):
+ def _modify_connection_params(self) -> None:
"""Modify connection parameters prior to SSH connection."""
- paramiko.Transport._preferred_kex = (
+ paramiko_transport = getattr(paramiko, "Transport")
+ paramiko_transport._preferred_kex = (
"diffie-hellman-group14-sha1",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group-exchange-sha256",
"diffie-hellman-group1-sha1",
)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
+ data = self._test_channel_read(pattern="to accept|[#$]")
# If "set post-login-banner enable" is set it will require you to press 'a'
# to accept the banner before you login. This will accept if it occurs
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "to accept" in output:
- self.write_channel("a\r")
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
-
- self._test_channel_read()
+ if "to accept" in data:
+ self.write_channel("a\r")
+ self._test_channel_read(pattern=r"[#$]")
+
self.set_base_prompt(alt_prompt_terminator="$")
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def disable_paging(self, delay_factor=1, **kwargs):
+ def disable_paging(
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Disable paging is only available with specific roles so it may fail."""
check_command = "get system status | grep Virtual"
- output = self.send_command_timing(check_command)
+ output = self._send_command_timing_str(check_command)
self.allow_disable_global = True
self.vdoms = False
self._output_mode = "more"
@@ -73,10 +71,11 @@
Module netmiko.fortinet.fortinet_ssh
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)
+ output = self._send_command_timing_str(vdom_additional_command, last_read=3)
if "Command fail" in output:
self.allow_disable_global = False
- self.remote_conn.close()
+ if self.remote_conn is not None:
+ self.remote_conn.close()
self.establish_connection(width=100, height=1000)
new_output = ""
@@ -91,7 +90,7 @@
Module netmiko.fortinet.fortinet_ssh
if self.vdoms:
disable_paging_commands.append("end")
outputlist = [
- self.send_command_timing(command, delay_factor=2)
+ self._send_command_timing_str(command, last_read=3)
for command in disable_paging_commands
]
# Should test output is valid
@@ -99,17 +98,17 @@
Module netmiko.fortinet.fortinet_ssh
return output + new_output
- def _retrieve_output_mode(self):
+ def _retrieve_output_mode(self) -> None:
"""Save the state of the output mode so it can be reset at the end of the session."""
reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n")
- output = self.send_command("get system console")
+ output = self._send_command_str("get system console")
result_mode_re = reg_mode.search(output)
if result_mode_re:
result_mode = result_mode_re.group("mode").strip()
if result_mode in ["more", "standard"]:
self._output_mode = result_mode
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Re-enable paging globally."""
if self.allow_disable_global:
# Return paging state
@@ -122,15 +121,9 @@
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class FortinetSSH(CiscoSSHConnection):
- def _modify_connection_params(self):
+
class FortinetSSH(NoConfig, CiscoSSHConnection):
+ def _modify_connection_params(self) -> None:
"""Modify connection parameters prior to SSH connection."""
- paramiko.Transport._preferred_kex = (
+ paramiko_transport = getattr(paramiko, "Transport")
+ paramiko_transport._preferred_kex = (
"diffie-hellman-group14-sha1",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group-exchange-sha256",
"diffie-hellman-group1-sha1",
)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
+ data = self._test_channel_read(pattern="to accept|[#$]")
# If "set post-login-banner enable" is set it will require you to press 'a'
# to accept the banner before you login. This will accept if it occurs
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "to accept" in output:
- self.write_channel("a\r")
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
-
- self._test_channel_read()
+ if "to accept" in data:
+ self.write_channel("a\r")
+ self._test_channel_read(pattern=r"[#$]")
+
self.set_base_prompt(alt_prompt_terminator="$")
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def disable_paging(self, delay_factor=1, **kwargs):
+ def disable_paging(
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Disable paging is only available with specific roles so it may fail."""
check_command = "get system status | grep Virtual"
- output = self.send_command_timing(check_command)
+ output = self._send_command_timing_str(check_command)
self.allow_disable_global = True
self.vdoms = False
self._output_mode = "more"
@@ -327,10 +294,11 @@
Classes
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)
+ output = self._send_command_timing_str(vdom_additional_command, last_read=3)
if "Command fail" in output:
self.allow_disable_global = False
- self.remote_conn.close()
+ if self.remote_conn is not None:
+ self.remote_conn.close()
self.establish_connection(width=100, height=1000)
new_output = ""
@@ -345,7 +313,7 @@
Classes
if self.vdoms:
disable_paging_commands.append("end")
outputlist = [
- self.send_command_timing(command, delay_factor=2)
+ self._send_command_timing_str(command, last_read=3)
for command in disable_paging_commands
]
# Should test output is valid
@@ -353,17 +321,17 @@
Classes
return output + new_output
- def _retrieve_output_mode(self):
+ def _retrieve_output_mode(self) -> None:
"""Save the state of the output mode so it can be reset at the end of the session."""
reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n")
- output = self.send_command("get system console")
+ output = self._send_command_str("get system console")
result_mode_re = reg_mode.search(output)
if result_mode_re:
result_mode = result_mode_re.group("mode").strip()
if result_mode in ["more", "standard"]:
self._output_mode = result_mode
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Re-enable paging globally."""
if self.allow_disable_global:
# Return paging state
@@ -376,20 +344,15 @@
def disable_paging(
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+) -> str:
"""Disable paging is only available with specific roles so it may fail."""
check_command = "get system status | grep Virtual"
- output = self.send_command_timing(check_command)
+ output = self._send_command_timing_str(check_command)
self.allow_disable_global = True
self.vdoms = False
self._output_mode = "more"
@@ -447,10 +404,11 @@
Methods
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)
+ output = self._send_command_timing_str(vdom_additional_command, last_read=3)
if "Command fail" in output:
self.allow_disable_global = False
- self.remote_conn.close()
+ if self.remote_conn is not None:
+ self.remote_conn.close()
self.establish_connection(width=100, height=1000)
new_output = ""
@@ -465,7 +423,7 @@
Methods
if self.vdoms:
disable_paging_commands.append("end")
outputlist = [
- self.send_command_timing(command, delay_factor=2)
+ self._send_command_timing_str(command, last_read=3)
for command in disable_paging_commands
]
# Should test output is valid
@@ -474,26 +432,16 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
+ data = self._test_channel_read(pattern="to accept|[#$]")
# If "set post-login-banner enable" is set it will require you to press 'a'
# to accept the banner before you login. This will accept if it occurs
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "to accept" in output:
- self.write_channel("a\r")
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
+ if "to accept" in data:
+ self.write_channel("a\r")
+ self._test_channel_read(pattern=r"[#$]")
- self._test_channel_read()
self.set_base_prompt(alt_prompt_terminator="$")
- self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class FortinetSSH(CiscoSSHConnection):
- def _modify_connection_params(self):
+
class FortinetSSH(NoConfig, CiscoSSHConnection):
+ def _modify_connection_params(self) -> None:
"""Modify connection parameters prior to SSH connection."""
- paramiko.Transport._preferred_kex = (
+ paramiko_transport = getattr(paramiko, "Transport")
+ paramiko_transport._preferred_kex = (
"diffie-hellman-group14-sha1",
"diffie-hellman-group-exchange-sha1",
"diffie-hellman-group-exchange-sha256",
"diffie-hellman-group1-sha1",
)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
+ data = self._test_channel_read(pattern="to accept|[#$]")
# If "set post-login-banner enable" is set it will require you to press 'a'
# to accept the banner before you login. This will accept if it occurs
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "to accept" in output:
- self.write_channel("a\r")
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
-
- self._test_channel_read()
+ if "to accept" in data:
+ self.write_channel("a\r")
+ self._test_channel_read(pattern=r"[#$]")
+
self.set_base_prompt(alt_prompt_terminator="$")
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def disable_paging(self, delay_factor=1, **kwargs):
+ def disable_paging(
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Disable paging is only available with specific roles so it may fail."""
check_command = "get system status | grep Virtual"
- output = self.send_command_timing(check_command)
+ output = self._send_command_timing_str(check_command)
self.allow_disable_global = True
self.vdoms = False
self._output_mode = "more"
@@ -226,10 +200,11 @@
Classes
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)
+ output = self._send_command_timing_str(vdom_additional_command, last_read=3)
if "Command fail" in output:
self.allow_disable_global = False
- self.remote_conn.close()
+ if self.remote_conn is not None:
+ self.remote_conn.close()
self.establish_connection(width=100, height=1000)
new_output = ""
@@ -244,7 +219,7 @@
Classes
if self.vdoms:
disable_paging_commands.append("end")
outputlist = [
- self.send_command_timing(command, delay_factor=2)
+ self._send_command_timing_str(command, last_read=3)
for command in disable_paging_commands
]
# Should test output is valid
@@ -252,17 +227,17 @@
Classes
return output + new_output
- def _retrieve_output_mode(self):
+ def _retrieve_output_mode(self) -> None:
"""Save the state of the output mode so it can be reset at the end of the session."""
reg_mode = re.compile(r"output\s+:\s+(?P<mode>.*)\s+\n")
- output = self.send_command("get system console")
+ output = self._send_command_str("get system console")
result_mode_re = reg_mode.search(output)
if result_mode_re:
result_mode = result_mode_re.group("mode").strip()
if result_mode in ["more", "standard"]:
self._output_mode = result_mode
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Re-enable paging globally."""
if self.allow_disable_global:
# Return paging state
@@ -275,20 +250,15 @@
def disable_paging(
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+) -> str:
"""Disable paging is only available with specific roles so it may fail."""
check_command = "get system status | grep Virtual"
- output = self.send_command_timing(check_command)
+ output = self._send_command_timing_str(check_command)
self.allow_disable_global = True
self.vdoms = False
self._output_mode = "more"
@@ -346,10 +310,11 @@
Methods
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)
+ output = self._send_command_timing_str(vdom_additional_command, last_read=3)
if "Command fail" in output:
self.allow_disable_global = False
- self.remote_conn.close()
+ if self.remote_conn is not None:
+ self.remote_conn.close()
self.establish_connection(width=100, height=1000)
new_output = ""
@@ -364,7 +329,7 @@
Methods
if self.vdoms:
disable_paging_commands.append("end")
outputlist = [
- self.send_command_timing(command, delay_factor=2)
+ self._send_command_timing_str(command, last_read=3)
for command in disable_paging_commands
]
# Should test output is valid
@@ -373,26 +338,16 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
+ data = self._test_channel_read(pattern="to accept|[#$]")
# If "set post-login-banner enable" is set it will require you to press 'a'
# to accept the banner before you login. This will accept if it occurs
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "to accept" in output:
- self.write_channel("a\r")
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
+ if "to accept" in data:
+ self.write_channel("a\r")
+ self._test_channel_read(pattern=r"[#$]")
- self._test_channel_read()
self.set_base_prompt(alt_prompt_terminator="$")
- self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
import re
+from typing import Union, Sequence, TextIO, Any, Optional
+
from netmiko.cisco_base_connection import CiscoSSHConnection
class HPComwareBase(CiscoSSHConnection):
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# Comware doesn't have a way to set terminal width which breaks cmd_verify
global_cmd_verify = kwargs.get("global_cmd_verify")
if global_cmd_verify is None:
kwargs["global_cmd_verify"] = False
- return super().__init__(**kwargs)
+ super().__init__(**kwargs)
- def session_preparation(self):
- """
- Prepare the session after the connection has been established.
- Extra time to read HP banners.
- """
- delay_factor = self.select_delay_factor(delay_factor=0)
- i = 1
- while i <= 4:
- # Comware can have a banner that prompts you to continue
- # 'Press Y or ENTER to continue, N to exit.'
- time.sleep(0.5 * delay_factor)
+ def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ # Comware can have a banner that prompts you to continue
+ # 'Press Y or ENTER to continue, N to exit.'
+ data = self._test_channel_read(pattern=r"to continue|[>\]]")
+ if "continue" in data:
self.write_channel("\n")
- i += 1
+ self._test_channel_read(pattern=r"[>\]]")
- time.sleep(0.3 * delay_factor)
- self.clear_buffer()
- self._test_channel_read(pattern=r"[>\]]")
self.set_base_prompt()
command = self.RETURN + "screen-length disable"
self.disable_paging(command=command)
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def config_mode(self, config_command="system-view"):
- """Enter configuration mode."""
- return super().config_mode(config_command=config_command)
+ def config_mode(
+ self, config_command: str = "system-view", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
- def exit_config_mode(self, exit_config="return", pattern=r">"):
+ def exit_config_mode(self, exit_config: str = "return", pattern: str = r">") -> str:
"""Exit config mode."""
return super().exit_config_mode(exit_config=exit_config, pattern=pattern)
- def check_config_mode(self, check_string="]"):
+ def check_config_mode(self, check_string: str = "]", pattern: str = "") -> bool:
"""Check whether device is in configuration mode. Return a boolean."""
return super().check_config_mode(check_string=check_string)
+ def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = True,
+ read_timeout: Optional[float] = None,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = False,
+ strip_command: bool = False,
+ config_mode_command: Optional[str] = None,
+ cmd_verify: bool = True,
+ enter_config_mode: bool = True,
+ error_pattern: str = "",
+ terminator: str = r"\]",
+ bypass_commands: Optional[str] = None,
+ ) -> str:
+ return super().send_config_set(
+ config_commands=config_commands,
+ exit_config_mode=exit_config_mode,
+ read_timeout=read_timeout,
+ delay_factor=delay_factor,
+ max_loops=max_loops,
+ strip_prompt=strip_prompt,
+ strip_command=strip_command,
+ config_mode_command=config_mode_command,
+ cmd_verify=cmd_verify,
+ enter_config_mode=enter_config_mode,
+ error_pattern=error_pattern,
+ terminator=terminator,
+ bypass_commands=bypass_commands,
+ )
+
def set_base_prompt(
- self, pri_prompt_terminator=">", alt_prompt_terminator="]", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "]",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""
Sets self.base_prompt
@@ -87,6 +117,7 @@
Module netmiko.hp.hp_comware
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
# Strip off leading character
@@ -95,19 +126,27 @@
class HPComwareTelnet(HPComwareBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
@@ -144,181 +183,182 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HPComwareBase(CiscoSSHConnection):
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# Comware doesn't have a way to set terminal width which breaks cmd_verify
global_cmd_verify = kwargs.get("global_cmd_verify")
if global_cmd_verify is None:
kwargs["global_cmd_verify"] = False
- return super().__init__(**kwargs)
+ super().__init__(**kwargs)
- def session_preparation(self):
- """
- Prepare the session after the connection has been established.
- Extra time to read HP banners.
- """
- delay_factor = self.select_delay_factor(delay_factor=0)
- i = 1
- while i <= 4:
- # Comware can have a banner that prompts you to continue
- # 'Press Y or ENTER to continue, N to exit.'
- time.sleep(0.5 * delay_factor)
+ def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ # Comware can have a banner that prompts you to continue
+ # 'Press Y or ENTER to continue, N to exit.'
+ data = self._test_channel_read(pattern=r"to continue|[>\]]")
+ if "continue" in data:
self.write_channel("\n")
- i += 1
+ self._test_channel_read(pattern=r"[>\]]")
- time.sleep(0.3 * delay_factor)
- self.clear_buffer()
- self._test_channel_read(pattern=r"[>\]]")
self.set_base_prompt()
command = self.RETURN + "screen-length disable"
self.disable_paging(command=command)
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def config_mode(self, config_command="system-view"):
- """Enter configuration mode."""
- return super().config_mode(config_command=config_command)
+ def config_mode(
+ self, config_command: str = "system-view", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
- def exit_config_mode(self, exit_config="return", pattern=r">"):
+ def exit_config_mode(self, exit_config: str = "return", pattern: str = r">") -> str:
"""Exit config mode."""
return super().exit_config_mode(exit_config=exit_config, pattern=pattern)
- def check_config_mode(self, check_string="]"):
+ def check_config_mode(self, check_string: str = "]", pattern: str = "") -> bool:
"""Check whether device is in configuration mode. Return a boolean."""
return super().check_config_mode(check_string=check_string)
+ def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = True,
+ read_timeout: Optional[float] = None,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = False,
+ strip_command: bool = False,
+ config_mode_command: Optional[str] = None,
+ cmd_verify: bool = True,
+ enter_config_mode: bool = True,
+ error_pattern: str = "",
+ terminator: str = r"\]",
+ bypass_commands: Optional[str] = None,
+ ) -> str:
+ return super().send_config_set(
+ config_commands=config_commands,
+ exit_config_mode=exit_config_mode,
+ read_timeout=read_timeout,
+ delay_factor=delay_factor,
+ max_loops=max_loops,
+ strip_prompt=strip_prompt,
+ strip_command=strip_command,
+ config_mode_command=config_mode_command,
+ cmd_verify=cmd_verify,
+ enter_config_mode=enter_config_mode,
+ error_pattern=error_pattern,
+ terminator=terminator,
+ bypass_commands=bypass_commands,
+ )
+
def set_base_prompt(
- self, pri_prompt_terminator=">", alt_prompt_terminator="]", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "]",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""
Sets self.base_prompt
@@ -333,6 +373,7 @@
Classes
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
# Strip off leading character
@@ -341,19 +382,27 @@
Prepare the session after the connection has been established.
-Extra time to read HP banners.
+
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
- """
- Prepare the session after the connection has been established.
- Extra time to read HP banners.
- """
- delay_factor = self.select_delay_factor(delay_factor=0)
- i = 1
- while i <= 4:
- # Comware can have a banner that prompts you to continue
- # 'Press Y or ENTER to continue, N to exit.'
- time.sleep(0.5 * delay_factor)
+
def session_preparation(self) -> None:
+ """Prepare the session after the connection has been established."""
+ # Comware can have a banner that prompts you to continue
+ # 'Press Y or ENTER to continue, N to exit.'
+ data = self._test_channel_read(pattern=r"to continue|[>\]]")
+ if "continue" in data:
self.write_channel("\n")
- i += 1
+ self._test_channel_read(pattern=r"[>\]]")
- time.sleep(0.3 * delay_factor)
- self.clear_buffer()
- self._test_channel_read(pattern=r"[>\]]")
self.set_base_prompt()
command = self.RETURN + "screen-length disable"
- self.disable_paging(command=command)
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
# Strip off leading character
@@ -535,8 +573,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HPComwareTelnet(HPComwareBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
import time
import socket
from os import path
+from typing import Optional
+
from paramiko import SSHClient
+from netmiko.ssh_auth import SSHClient_noauth
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko import log
-
-
-class SSHClient_noauth(SSHClient):
- """Set noauth when manually handling SSH authentication."""
-
- def _auth(self, username, *args):
- self._transport.auth_none(username)
- return
+from netmiko.exceptions import ReadTimeout
class HPProcurveBase(CiscoSSHConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
"""
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
- self._test_channel_read(pattern=r"[>#]")
+ # Procurve over SSH uses 'Press any key to continue'
+ data = self._test_channel_read(pattern=r"(any key to continue|[>#])")
+ if "any key to continue" in data:
+ self.write_channel(self.RETURN)
+ self._test_channel_read(pattern=r"[>#]")
+
self.set_base_prompt()
- command = self.RETURN + "no page"
self.set_terminal_width(command="terminal width 511", pattern="terminal")
+ command = self.RETURN + "no page"
self.disable_paging(command=command)
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[>#]"
+ ) -> bool:
+ """
+ The pattern is needed as it is not in the parent class.
+
+ Not having this will make each check_config_mode() call take ~2 seconds.
+ """
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
def enable(
self,
- cmd="enable",
- pattern="password",
- re_flags=re.IGNORECASE,
- default_username="manager",
- ):
+ cmd: str = "enable",
+ pattern: str = "password",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ default_username: str = "manager",
+ ) -> str:
"""Enter enable mode"""
- delay_factor = self.select_delay_factor(delay_factor=0)
+
if self.check_enable_mode():
return ""
output = ""
- i = 1
- max_attempts = 5
- while i <= max_attempts:
- self.write_channel(cmd + self.RETURN)
- time.sleep(0.3 * delay_factor)
- new_output = self.read_channel()
- username_pattern = r"(username|login|user name)"
- if re.search(username_pattern, new_output, flags=re_flags):
- output += new_output
- new_output = self.send_command_timing(default_username)
- if re.search(pattern, new_output, flags=re_flags):
- output += new_output
- self.write_channel(self.normalize_cmd(self.secret))
- new_output = self._read_channel_timing()
- if self.check_enable_mode():
- output += new_output
- return output
+ username_pattern = r"(username|login|user name)"
+ pwd_pattern = pattern
+ prompt_pattern = r"[>#]"
+ full_pattern = rf"(username|login|user name|{pwd_pattern}|{prompt_pattern})"
+
+ # Send the enable command
+ self.write_channel(cmd + self.RETURN)
+ new_output = self.read_until_pattern(
+ full_pattern, read_timeout=15, re_flags=re_flags
+ )
+
+ # Send the username
+ if re.search(username_pattern, new_output, flags=re_flags):
output += new_output
- i += 1
+ self.write_channel(default_username + self.RETURN)
+ full_pattern = rf"{pwd_pattern}|{prompt_pattern})"
+ new_output = self.read_until_pattern(
+ full_pattern, read_timeout=15, re_flags=re_flags
+ )
+
+ # Send the password
+ if re.search(pwd_pattern, new_output, flags=re_flags):
+ output += new_output
+ self.write_channel(self.secret + self.RETURN)
+ new_output = self.read_until_pattern(
+ prompt_pattern, read_timeout=15, re_flags=re_flags
+ )
+ output += new_output
log.debug(f"{output}")
self.clear_buffer()
msg = (
@@ -99,50 +117,54 @@
Module netmiko.hp.hp_procurve
raise ValueError(msg)
return output
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Gracefully exit the SSH session."""
# Exit configuration mode.
try:
- # The pattern="" forces use of send_command_timing
- if self.check_config_mode(pattern=""):
+ if self.check_config_mode():
self.exit_config_mode()
except Exception:
pass
# Terminate SSH/telnet session
self.write_channel(command + self.RETURN)
- count = 0
+
output = ""
- while count <= 5:
- time.sleep(0.5)
+ for _ in range(10):
# The connection might be dead here.
try:
- new_output = self.read_channel()
+ # "Do you want to log out"
+ # "Do you want to save the current"
+ pattern = r"Do you want.*"
+ new_output = self.read_until_pattern(pattern, read_timeout=1.5)
output += new_output
- except socket.error:
- break
-
- if "Do you want to log out" in new_output:
- self.write_channel("y" + self.RETURN)
- time.sleep(0.5)
- output += self.read_channel()
- # Don't automatically save the config (user's responsibility)
- if "Do you want to save the current" in output:
- self.write_channel("n" + self.RETURN)
-
- try:
- self.write_channel(self.RETURN)
+ if "Do you want to log out" in new_output:
+ self.write_channel("y" + self.RETURN)
+ break
+ elif "Do you want to save the current" in new_output:
+ # Don't automatically save the config (user's responsibility)
+ self.write_channel("n" + self.RETURN)
except socket.error:
break
- count += 1
+ except ReadTimeout:
+ break
+ except Exception:
+ break
+
+ time.sleep(0.05)
# Set outside of loop
self._session_log_fin = True
- def save_config(self, cmd="write memory", confirm=False, confirm_response=""):
+ def save_config(
+ self,
+ cmd: str = "write memory",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Save Config."""
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
@@ -150,32 +172,11 @@
Module netmiko.hp.hp_procurve
class HPProcurveSSH(HPProcurveBase):
- def session_preparation(self):
- """
- Prepare the session after the connection has been established.
- """
- # Procurve over SHH uses 'Press any key to continue'
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "any key to continue" in output:
- self.write_channel(self.RETURN)
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
-
- # Try one last time to past "Press any key to continue
- self.write_channel(self.RETURN)
-
- super().session_preparation()
-
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Allow passwordless authentication for HP devices being provisioned."""
# Create instance of SSHClient object. If no SSH keys and no password, then use noauth
+ remote_conn_pre: SSHClient
if not self.use_keys and not self.password:
remote_conn_pre = SSHClient_noauth()
else:
@@ -195,15 +196,15 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HPProcurveBase(CiscoSSHConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
"""
# HP output contains VT100 escape codes
self.ansi_escape_codes = True
- self._test_channel_read(pattern=r"[>#]")
+ # Procurve over SSH uses 'Press any key to continue'
+ data = self._test_channel_read(pattern=r"(any key to continue|[>#])")
+ if "any key to continue" in data:
+ self.write_channel(self.RETURN)
+ self._test_channel_read(pattern=r"[>#]")
+
self.set_base_prompt()
- command = self.RETURN + "no page"
self.set_terminal_width(command="terminal width 511", pattern="terminal")
+ command = self.RETURN + "no page"
self.disable_paging(command=command)
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
+
+ def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[>#]"
+ ) -> bool:
+ """
+ The pattern is needed as it is not in the parent class.
+
+ Not having this will make each check_config_mode() call take ~2 seconds.
+ """
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
def enable(
self,
- cmd="enable",
- pattern="password",
- re_flags=re.IGNORECASE,
- default_username="manager",
- ):
+ cmd: str = "enable",
+ pattern: str = "password",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ default_username: str = "manager",
+ ) -> str:
"""Enter enable mode"""
- delay_factor = self.select_delay_factor(delay_factor=0)
+
if self.check_enable_mode():
return ""
output = ""
- i = 1
- max_attempts = 5
- while i <= max_attempts:
- self.write_channel(cmd + self.RETURN)
- time.sleep(0.3 * delay_factor)
- new_output = self.read_channel()
- username_pattern = r"(username|login|user name)"
- if re.search(username_pattern, new_output, flags=re_flags):
- output += new_output
- new_output = self.send_command_timing(default_username)
- if re.search(pattern, new_output, flags=re_flags):
- output += new_output
- self.write_channel(self.normalize_cmd(self.secret))
- new_output = self._read_channel_timing()
- if self.check_enable_mode():
- output += new_output
- return output
+ username_pattern = r"(username|login|user name)"
+ pwd_pattern = pattern
+ prompt_pattern = r"[>#]"
+ full_pattern = rf"(username|login|user name|{pwd_pattern}|{prompt_pattern})"
+
+ # Send the enable command
+ self.write_channel(cmd + self.RETURN)
+ new_output = self.read_until_pattern(
+ full_pattern, read_timeout=15, re_flags=re_flags
+ )
+
+ # Send the username
+ if re.search(username_pattern, new_output, flags=re_flags):
output += new_output
- i += 1
+ self.write_channel(default_username + self.RETURN)
+ full_pattern = rf"{pwd_pattern}|{prompt_pattern})"
+ new_output = self.read_until_pattern(
+ full_pattern, read_timeout=15, re_flags=re_flags
+ )
+
+ # Send the password
+ if re.search(pwd_pattern, new_output, flags=re_flags):
+ output += new_output
+ self.write_channel(self.secret + self.RETURN)
+ new_output = self.read_until_pattern(
+ prompt_pattern, read_timeout=15, re_flags=re_flags
+ )
+ output += new_output
log.debug(f"{output}")
self.clear_buffer()
msg = (
@@ -420,50 +416,54 @@
Classes
raise ValueError(msg)
return output
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Gracefully exit the SSH session."""
# Exit configuration mode.
try:
- # The pattern="" forces use of send_command_timing
- if self.check_config_mode(pattern=""):
+ if self.check_config_mode():
self.exit_config_mode()
except Exception:
pass
# Terminate SSH/telnet session
self.write_channel(command + self.RETURN)
- count = 0
+
output = ""
- while count <= 5:
- time.sleep(0.5)
+ for _ in range(10):
# The connection might be dead here.
try:
- new_output = self.read_channel()
+ # "Do you want to log out"
+ # "Do you want to save the current"
+ pattern = r"Do you want.*"
+ new_output = self.read_until_pattern(pattern, read_timeout=1.5)
output += new_output
- except socket.error:
- break
-
- if "Do you want to log out" in new_output:
- self.write_channel("y" + self.RETURN)
- time.sleep(0.5)
- output += self.read_channel()
-
- # Don't automatically save the config (user's responsibility)
- if "Do you want to save the current" in output:
- self.write_channel("n" + self.RETURN)
- try:
- self.write_channel(self.RETURN)
+ if "Do you want to log out" in new_output:
+ self.write_channel("y" + self.RETURN)
+ break
+ elif "Do you want to save the current" in new_output:
+ # Don't automatically save the config (user's responsibility)
+ self.write_channel("n" + self.RETURN)
except socket.error:
break
- count += 1
+ except ReadTimeout:
+ break
+ except Exception:
+ break
+
+ time.sleep(0.05)
# Set outside of loop
self._session_log_fin = True
- def save_config(self, cmd="write memory", confirm=False, confirm_response=""):
+ def save_config(
+ self,
+ cmd: str = "write memory",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Save Config."""
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
@@ -482,8 +482,27 @@
The pattern is needed as it is not in the parent class.
+
Not having this will make each check_config_mode() call take ~2 seconds.
+
+Source code
+
def check_config_mode(
+ self, check_string: str = ")#", pattern: str = r"[>#]"
+) -> bool:
+ """
+ The pattern is needed as it is not in the parent class.
+
+ Not having this will make each check_config_mode() call take ~2 seconds.
+ """
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HPProcurveSSH(HPProcurveBase):
- def session_preparation(self):
- """
- Prepare the session after the connection has been established.
- """
- # Procurve over SHH uses 'Press any key to continue'
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "any key to continue" in output:
- self.write_channel(self.RETURN)
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
-
- # Try one last time to past "Press any key to continue
- self.write_channel(self.RETURN)
-
- super().session_preparation()
-
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Allow passwordless authentication for HP devices being provisioned."""
# Create instance of SSHClient object. If no SSH keys and no password, then use noauth
+ remote_conn_pre: SSHClient
if not self.use_keys and not self.password:
remote_conn_pre = SSHClient_noauth()
else:
@@ -809,13 +796,12 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HPComwareTelnet(HPComwareBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HPProcurveSSH(HPProcurveBase):
- def session_preparation(self):
- """
- Prepare the session after the connection has been established.
- """
- # Procurve over SHH uses 'Press any key to continue'
- delay_factor = self.select_delay_factor(delay_factor=0)
- output = ""
- count = 1
- while count <= 30:
- output += self.read_channel()
- if "any key to continue" in output:
- self.write_channel(self.RETURN)
- break
- else:
- time.sleep(0.33 * delay_factor)
- count += 1
-
- # Try one last time to past "Press any key to continue
- self.write_channel(self.RETURN)
-
- super().session_preparation()
-
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> SSHClient:
"""Allow passwordless authentication for HP devices being provisioned."""
# Create instance of SSHClient object. If no SSH keys and no password, then use noauth
+ remote_conn_pre: SSHClient
if not self.use_keys and not self.password:
remote_conn_pre = SSHClient_noauth()
else:
@@ -636,13 +534,12 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
from typing import Optional, Any
+import time
import re
+import warnings
+
+from netmiko.no_enable import NoEnable
+from netmiko.base_connection import DELAY_FACTOR_DEPR_SIMPLE_MSG
from netmiko.cisco_base_connection import CiscoBaseConnection
-from netmiko.ssh_exception import NetmikoAuthenticationException
+from netmiko.exceptions import NetmikoAuthenticationException
from netmiko import log
-class HuaweiBase(CiscoBaseConnection):
- def session_preparation(self):
+class HuaweiBase(NoEnable, CiscoBaseConnection):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>\]]")
self.set_base_prompt()
self.disable_paging(command="screen-length 0 temporary")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -54,33 +56,31 @@
This will be set on logging in, but not when entering system-view
"""
- # log.debug("In set_base_prompt")
- delay_factor = self.select_delay_factor(delay_factor)
- self.clear_buffer()
- self.write_channel(self.RETURN)
- time.sleep(0.5 * delay_factor)
-
- prompt = self.read_channel()
- prompt = self.normalize_linefeeds(prompt)
- # If multiple lines in the output take the last line
- prompt = prompt.split(self.RESPONSE_RETURN)[-1]
- prompt = prompt.strip()
-
- # Check that ends with a valid terminator character
- if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
- raise ValueError(f"Router prompt not found: {prompt}")
+ prompt = super().set_base_prompt(
+ pri_prompt_terminator=pri_prompt_terminator,
+ alt_prompt_terminator=alt_prompt_terminator,
+ delay_factor=delay_factor,
+ pattern=pattern,
+ )
# Strip off any leading HRP_. characters for USGv5 HA
prompt = re.sub(r"^HRP_.", "", prompt, flags=re.M)
- # Strip off leading and trailing terminator
- prompt = prompt[1:-1]
+ # Strip off leading terminator
+ prompt = prompt[1:]
prompt = prompt.strip()
self.base_prompt = prompt
log.debug(f"prompt: {self.base_prompt}")
-
return self.base_prompt
- def save_config(self, cmd="save", confirm=True, confirm_response="y"):
- """ Save Config for HuaweiSSH"""
+ def save_config(
+ self, cmd: str = "save", confirm: bool = True, confirm_response: str = "y"
+ ) -> str:
+ """Save Config for HuaweiSSH"""
return super().save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
)
@@ -129,7 +121,7 @@
Module netmiko.huawei.huawei
class HuaweiSSH(HuaweiBase):
"""Huawei SSH driver."""
- def special_login_handler(self):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handle password change request by ignoring it"""
# Huawei can prompt for password change. Search for that or for normal prompt
@@ -138,7 +130,7 @@
Module netmiko.huawei.huawei
if re.search(password_change_prompt, output):
self.write_channel("N\n")
self.clear_buffer()
- return output
+ return None
class HuaweiTelnet(HuaweiBase):
@@ -146,13 +138,13 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class HuaweiBase(CiscoBaseConnection):
- def session_preparation(self):
+
class HuaweiBase(NoEnable, CiscoBaseConnection):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>\]]")
self.set_base_prompt()
self.disable_paging(command="screen-length 0 temporary")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -430,33 +411,31 @@
This will be set on logging in, but not when entering system-view
"""
- # log.debug("In set_base_prompt")
- delay_factor = self.select_delay_factor(delay_factor)
- self.clear_buffer()
- self.write_channel(self.RETURN)
- time.sleep(0.5 * delay_factor)
-
- prompt = self.read_channel()
- prompt = self.normalize_linefeeds(prompt)
-
- # If multiple lines in the output take the last line
- prompt = prompt.split(self.RESPONSE_RETURN)[-1]
- prompt = prompt.strip()
- # Check that ends with a valid terminator character
- if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
- raise ValueError(f"Router prompt not found: {prompt}")
+ prompt = super().set_base_prompt(
+ pri_prompt_terminator=pri_prompt_terminator,
+ alt_prompt_terminator=alt_prompt_terminator,
+ delay_factor=delay_factor,
+ pattern=pattern,
+ )
# Strip off any leading HRP_. characters for USGv5 HA
prompt = re.sub(r"^HRP_.", "", prompt, flags=re.M)
- # Strip off leading and trailing terminator
- prompt = prompt[1:-1]
+ # Strip off leading terminator
+ prompt = prompt[1:]
prompt = prompt.strip()
self.base_prompt = prompt
log.debug(f"prompt: {self.base_prompt}")
-
return self.base_prompt
def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -699,20 +616,23 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HuaweiSSH(HuaweiBase):
"""Huawei SSH driver."""
- def special_login_handler(self):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handle password change request by ignoring it"""
# Huawei can prompt for password change. Search for that or for normal prompt
@@ -884,11 +778,12 @@
Inherited members
if re.search(password_change_prompt, output):
self.write_channel("N\n")
self.clear_buffer()
- return output
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handle password change request by ignoring it"""
# Huawei can prompt for password change. Search for that or for normal prompt
@@ -914,7 +809,7 @@
Methods
if re.search(password_change_prompt, output):
self.write_channel("N\n")
self.clear_buffer()
- return output
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
import time
import re
+from typing import Optional
+
from netmiko.cisco_base_connection import CiscoBaseConnection
from netmiko import log
@@ -31,18 +33,15 @@
Module netmiko.huawei.huawei_smartax
class HuaweiSmartAXSSH(CiscoBaseConnection):
"""Supports Huawei SmartAX and OLT."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self._disable_smart_interaction()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -58,7 +57,9 @@
Module netmiko.huawei.huawei_smartax
log.debug(f"repr = {repr(output)}")
return super().strip_ansi_escape_codes(output)
- def _disable_smart_interaction(self, command="undo smart", delay_factor=1):
+ def _disable_smart_interaction(
+ self, command: str = "undo smart", delay_factor: float = 1.0
+ ) -> None:
"""Disables the { <cr> } prompt to avoid having to sent a 2nd return after each command"""
delay_factor = self.select_delay_factor(delay_factor)
time.sleep(delay_factor * 0.1)
@@ -69,38 +70,73 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HuaweiSmartAXSSH(CiscoBaseConnection):
"""Supports Huawei SmartAX and OLT."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self._disable_smart_interaction()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -283,7 +289,9 @@
Classes
log.debug(f"repr = {repr(output)}")
return super().strip_ansi_escape_codes(output)
- def _disable_smart_interaction(self, command="undo smart", delay_factor=1):
+ def _disable_smart_interaction(
+ self, command: str = "undo smart", delay_factor: float = 1.0
+ ) -> None:
"""Disables the { <cr> } prompt to avoid having to sent a 2nd return after each command"""
delay_factor = self.select_delay_factor(delay_factor)
time.sleep(delay_factor * 0.1)
@@ -294,38 +302,73 @@
def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -417,8 +447,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HuaweiSSH(HuaweiBase):
"""Huawei SSH driver."""
- def special_login_handler(self):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handle password change request by ignoring it"""
# Huawei can prompt for password change. Search for that or for normal prompt
@@ -199,11 +172,12 @@
Classes
if re.search(password_change_prompt, output):
self.write_channel("N\n")
self.clear_buffer()
- return output
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handle password change request by ignoring it"""
# Huawei can prompt for password change. Search for that or for normal prompt
@@ -229,7 +203,7 @@
Methods
if re.search(password_change_prompt, output):
self.write_channel("N\n")
self.clear_buffer()
- return output
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class HuaweiSmartAXSSH(CiscoBaseConnection):
"""Supports Huawei SmartAX and OLT."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- self._test_channel_read()
+ self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
self._disable_smart_interaction()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -449,7 +393,9 @@
Inherited members
log.debug(f"repr = {repr(output)}")
return super().strip_ansi_escape_codes(output)
- def _disable_smart_interaction(self, command="undo smart", delay_factor=1):
+ def _disable_smart_interaction(
+ self, command: str = "undo smart", delay_factor: float = 1.0
+ ) -> None:
"""Disables the { <cr> } prompt to avoid having to sent a 2nd return after each command"""
delay_factor = self.select_delay_factor(delay_factor)
time.sleep(delay_factor * 0.1)
@@ -460,38 +406,73 @@
def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Huawei does a strange thing where they add a space and then add ESC[1D
to move the cursor to the left one.
@@ -583,8 +551,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Factory function selects the proper class and creates object based on device_type.
Source code
-
def ConnectHandler(*args, **kwargs):
+
def ConnectHandler(*args: Any, **kwargs: Any) -> "BaseConnection":
"""Factory function selects the proper class and creates object based on device_type."""
device_type = kwargs["device_type"]
if device_type not in platforms:
@@ -391,7 +527,7 @@
Functions
Factory function selects the proper SCP class and creates object based on device_type.
Source code
-
def FileTransfer(*args, **kwargs):
+
def FileTransfer(*args: Any, **kwargs: Any) -> "BaseFileTransfer":
"""Factory function selects the proper SCP class and creates object based on device_type."""
if len(args) >= 1:
device_type = args[0].device_type
@@ -402,6 +538,7 @@
Factory function selects the proper class and creates object based on device_type.
Source code
-
def ConnectHandler(*args, **kwargs):
+
def ConnectHandler(*args: Any, **kwargs: Any) -> "BaseConnection":
"""Factory function selects the proper class and creates object based on device_type."""
device_type = kwargs["device_type"]
if device_type not in platforms:
@@ -443,19 +580,19 @@
def redispatch(
+ obj: "BaseConnection", device_type: str, session_prep: bool = True
+) -> None:
"""Dynamically change Netmiko object's class to proper class.
Generally used with terminal_server device_type when you need to redispatch after interacting
with terminal server.
@@ -604,7 +751,7 @@
Functions
Select the class to be instantiated based on vendor/platform.
Source code
-
def ssh_dispatcher(device_type):
+
def ssh_dispatcher(device_type: str) -> Type["BaseConnection"]:
"""Select the class to be instantiated based on vendor/platform."""
return CLASS_MAPPER[device_type]
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
else:
self.protocol = "ssh"
+ self.key_policy: paramiko.client.MissingHostKeyPolicy
if not ssh_strict:
self.key_policy = paramiko.AutoAddPolicy()
else:
@@ -1056,6 +1174,7 @@
Classes
self.system_host_keys = system_host_keys
self.alt_host_keys = alt_host_keys
self.alt_key_file = alt_key_file
+ self.disabled_algorithms = disabled_algorithms or {}
# For SSH proxy support
self.ssh_config_file = ssh_config_file
@@ -1064,25 +1183,30 @@
Classes
if auto_connect:
self._open()
- def _open(self):
+ def _open(self) -> None:
"""Decouple connection creation from __init__ for mocking."""
self._modify_connection_params()
self.establish_connection()
self._try_session_preparation()
- def __enter__(self):
+ def __enter__(self) -> "BaseConnection":
"""Establish a session using a Context Manager."""
return self
- def __exit__(self, exc_type, exc_value, traceback):
+ def __exit__(
+ self,
+ exc_type: Optional[Type[BaseException]],
+ exc_value: Optional[BaseException],
+ traceback: Optional[TracebackType],
+ ) -> None:
"""Gracefully close connection on Context Manager exit."""
self.disconnect()
- def _modify_connection_params(self):
+ def _modify_connection_params(self) -> None:
"""Modify connection parameters prior to SSH connection."""
pass
- def _timeout_exceeded(self, start, msg="Timeout exceeded!"):
+ def _timeout_exceeded(self, start: float, msg: str = "Timeout exceeded!") -> bool:
"""Raise NetmikoTimeoutException if waiting too much in the serving queue.
:param start: Initial start time to see if session lock timeout has been exceeded
@@ -1099,7 +1223,7 @@
Classes
raise NetmikoTimeoutException(msg)
return False
- def _lock_netmiko_session(self, start=None):
+ def _lock_netmiko_session(self, start: Optional[float] = None) -> bool:
"""Try to acquire the Netmiko session lock. If not available, wait in the queue until
the channel is available again.
@@ -1115,68 +1239,33 @@
Classes
time.sleep(0.1)
return True
- def _unlock_netmiko_session(self):
+ def _unlock_netmiko_session(self) -> None:
"""
Release the channel at the end of the task.
"""
if self._session_locker.locked():
self._session_locker.release()
- def _write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+ def _autodetect_fs(self, cmd: str = "", pattern: str = "") -> str:
+ raise NotImplementedError
- :param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
- """
- if self.protocol == "ssh":
- self.remote_conn.sendall(write_bytes(out_data, encoding=self.encoding))
- elif self.protocol == "telnet":
- self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
- elif self.protocol == "serial":
- self.remote_conn.write(write_bytes(out_data, encoding=self.encoding))
- self.remote_conn.flush()
- else:
- raise ValueError("Invalid protocol specified")
- try:
- log.debug(
- "write_channel: {}".format(
- write_bytes(out_data, encoding=self.encoding)
- )
- )
- if self._session_log_fin or self.session_log_record_writes:
- self._write_session_log(out_data)
- except UnicodeDecodeError:
- # Don't log non-ASCII characters; this is null characters and telnet IAC (PY2)
- pass
+ def _enter_shell(self) -> str:
+ raise NotImplementedError
- def _write_session_log(self, data):
- if self.session_log is not None and len(data) > 0:
- # Hide the password and secret in the session_log
- if self.password:
- data = data.replace(self.password, "********")
- if self.secret:
- data = data.replace(self.secret, "********")
- if isinstance(self.session_log, io.BufferedIOBase):
- data = self.normalize_linefeeds(data)
- self.session_log.write(write_bytes(data, encoding=self.encoding))
- else:
- self.session_log.write(self.normalize_linefeeds(data))
- self.session_log.flush()
+ def _return_cli(self) -> str:
+ raise NotImplementedError
- def write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+ @lock_channel
+ @log_writes
+ def write_channel(self, out_data: str) -> None:
+ """Generic method that will write data out the channel.
:param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
+ :type out_data: str
"""
- self._lock_netmiko_session()
- try:
- self._write_channel(out_data)
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+ self.channel.write_channel(out_data)
- def is_alive(self):
+ def is_alive(self) -> bool:
"""Returns a boolean flag with the state of the connection."""
null = chr(0)
if self.remote_conn is None:
@@ -1188,9 +1277,11 @@
Classes
# IAC = Interpret as Command; it comes before the NOP.
log.debug("Sending IAC + NOP")
# Need to send multiple times to test connection
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
+ telnet_socket = self.remote_conn.get_socket()
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
return True
except AttributeError:
return False
@@ -1200,203 +1291,236 @@
Classes
# Try sending ASCII null byte to maintain the connection alive
log.debug("Sending the NULL byte")
self.write_channel(null)
- return self.remote_conn.transport.is_active()
+ assert isinstance(self.remote_conn, paramiko.Channel)
+ assert self.remote_conn.transport is not None
+ result = self.remote_conn.transport.is_active()
+ assert isinstance(result, bool)
+ return result
except (socket.error, EOFError):
log.error("Unable to send", exc_info=True)
# If unable to send, we can tell for sure that the connection is unusable
return False
return False
- def _read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- if self.protocol == "ssh":
- output = ""
- while True:
- if self.remote_conn.recv_ready():
- outbuf = self.remote_conn.recv(MAX_BUFFER)
- if len(outbuf) == 0:
- raise EOFError("Channel stream closed by remote device.")
- output += outbuf.decode("utf-8", "ignore")
- else:
- break
- elif self.protocol == "telnet":
- output = self.remote_conn.read_very_eager().decode("utf-8", "ignore")
- elif self.protocol == "serial":
- output = ""
- while self.remote_conn.in_waiting > 0:
- output += self.remote_conn.read(self.remote_conn.in_waiting).decode(
- "utf-8", "ignore"
- )
+ @lock_channel
+ def read_channel(self) -> str:
+ """Generic handler that will read all the data from given channel."""
+ new_data = self.channel.read_channel()
+ new_data = self.normalize_linefeeds(new_data)
if self.ansi_escape_codes:
- output = self.strip_ansi_escape_codes(output)
- log.debug(f"read_channel: {output}")
- self._write_session_log(output)
+ new_data = self.strip_ansi_escape_codes(new_data)
+ log.debug(f"read_channel: {new_data}")
+ if self.session_log:
+ self.session_log.write(new_data)
+
+ # If data had been previously saved to the buffer, the prepend it to output
+ # do post read_channel so session_log/log doesn't record buffered data twice
+ if self._read_buffer:
+ output = self._read_buffer + new_data
+ self._read_buffer = ""
+ else:
+ output = new_data
return output
- def read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- output = ""
- self._lock_netmiko_session()
- try:
- output = self._read_channel()
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
- return output
+ def read_until_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel until pattern is detected.
- def _read_channel_expect(self, pattern="", re_flags=0, max_loops=150):
- """Function that reads channel until pattern is detected.
+ Will return string up to and including pattern.
- pattern takes a regular expression.
+ Returns ReadTimeout if pattern not detected in read_timeout seconds.
- By default pattern will be self.base_prompt
+ :param pattern: Regular expression pattern used to identify that reading is done.
- Note: this currently reads beyond pattern. In the case of SSH it reads MAX_BUFFER.
- In the case of telnet it reads all non-blocking data.
+ :param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+ A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+ reading indefinitely until pattern is detected.
- There are dependencies here like determining whether in config_mode that are actually
- depending on reading beyond pattern.
+ :param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
- :param pattern: Regular expression pattern used to identify the command is done \
- (defaults to self.base_prompt)
- :type pattern: str (regular expression)
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of max_loops with read_until_pattern.
+You should convert all uses of max_loops over to read_timeout=x
+where x is the total number of seconds to wait before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
- :param max_loops: max number of iterations to read the channel before raising exception.
- Will default to be based upon self.timeout.
- :type max_loops: int
- """
output = ""
- if not pattern:
- pattern = re.escape(self.base_prompt)
- log.debug(f"Pattern is: {pattern}")
-
- i = 1
- loop_delay = 0.1
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # argument for backwards compatibility).
- if max_loops == 150:
- max_loops = int(self.timeout / loop_delay)
- while i < max_loops:
- if self.protocol == "ssh":
- try:
- # If no data available will wait timeout seconds trying to read
- self._lock_netmiko_session()
- new_data = self.remote_conn.recv(MAX_BUFFER)
- if len(new_data) == 0:
- raise EOFError("Channel stream closed by remote device.")
- new_data = new_data.decode("utf-8", "ignore")
- if self.ansi_escape_codes:
- new_data = self.strip_ansi_escape_codes(new_data)
- log.debug(f"_read_channel_expect read_data: {new_data}")
- output += new_data
- self._write_session_log(new_data)
- except socket.timeout:
- raise NetmikoTimeoutException(
- "Timed-out reading channel, data not available."
- )
- finally:
- self._unlock_netmiko_session()
- elif self.protocol == "telnet" or "serial":
- output += self.read_channel()
+ loop_delay = 0.01
+ start_time = time.time()
+ # if read_timeout == 0 or 0.0 keep reading indefinitely
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ output += self.read_channel()
if re.search(pattern, output, flags=re_flags):
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ # The string matched by pattern must be retained in the output string.
+ # re.split will do this if capturing parentesis are used.
+ if len(results) == 2:
+ # no capturing parenthesis, convert and try again.
+ pattern = f"({pattern})"
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ if len(results) != 3:
+ # well, we tried
+ msg = f"""Unable to successfully split output based on pattern:
+pattern={pattern}
+output={repr(output)}
+results={results}
+"""
+ raise ReadException(msg)
+
+ # Process such that everything before and including pattern is return.
+ # Everything else is retained in the _read_buffer
+ output, match_str, buffer = results
+ output = output + match_str
+ if buffer:
+ self._read_buffer += buffer
log.debug(f"Pattern found: {pattern} {output}")
return output
- time.sleep(loop_delay * self.global_delay_factor)
- i += 1
- raise NetmikoTimeoutException(
- f"Timed-out reading channel, pattern not found in output: {pattern}"
- )
+ time.sleep(loop_delay)
+
+ msg = f"""\n\nPattern not detected: {repr(pattern)} in output.
+
+Things you might try to fix this:
+1. Adjust the regex pattern to better identify the terminating string. Note, in
+many situations the pattern is automatically based on the network device's prompt.
+2. Increase the read_timeout to a larger value.
- def _read_channel_timing(self, delay_factor=1, max_loops=150):
+You can also look at the Netmiko session_log or debug log for more information.\n\n"""
+ raise ReadTimeout(msg)
+
+ def read_channel_timing(
+ self,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ ) -> str:
"""Read data on the channel based on timing delays.
- Attempt to read channel max_loops number of times. If no data this will cause a 15 second
- delay.
+ General pattern is keep reading until no new data is read.
+ Once no new data is read wait `last_read` amount of time (one last read).
+ As long as no new data, then return data.
- Once data is encountered read channel for another two seconds (2 * delay_factor) to make
- sure reading of channel is complete.
+ `read_timeout` is an absolute timer for how long to keep reading (which presupposes
+ we are still getting new data).
- :param delay_factor: multiplicative factor to adjust delay when reading channel (delays
- get multiplied by this factor)
- :type delay_factor: int or float
+ Setting `read_timeout` to zero will cause read_channel_timing to never expire based
+ on an absolute timeout. It will only complete based on timeout based on their being
+ no new data.
- :param max_loops: maximum number of loops to iterate through before returning channel data.
- Will default to be based upon self.timeout.
- :type max_loops: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
- # Time to delay in each read loop
- loop_delay = 0.1
- final_delay = 2
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 150:
- max_loops = int(self.timeout / loop_delay)
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
- # FIX: Cleanup in future versions of Netmiko
- if delay_factor < 1:
- if not self._legacy_mode and self.fast_cli:
- delay_factor = 1
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+ # Time to delay in each read loop
+ loop_delay = 0.1
channel_data = ""
- i = 0
- while i <= max_loops:
- time.sleep(loop_delay * delay_factor)
+ start_time = time.time()
+
+ # Set read_timeout to 0 to never timeout
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ time.sleep(loop_delay)
new_data = self.read_channel()
+ # gather new output
if new_data:
channel_data += new_data
- else:
- # Safeguard to make sure really done
- time.sleep(final_delay * delay_factor)
+ # if we have some output, but nothing new, then do the last read
+ elif channel_data != "":
+ # Make sure really done (i.e. no new data)
+ time.sleep(last_read)
new_data = self.read_channel()
if not new_data:
break
else:
channel_data += new_data
- i += 1
- return channel_data
+ else:
+ msg = f"""\n
+read_channel_timing's absolute timer expired.
- def read_until_prompt(self, *args, **kwargs):
- """Read channel until self.base_prompt detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+The network device was continually outputting data for longer than {read_timeout}
+seconds.
- def read_until_pattern(self, *args, **kwargs):
- """Read channel until pattern detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+If this is expected i.e. the command you are executing is continually emitting
+data for a long period of time, then you can set 'read_timeout=x' seconds. If
+you want Netmiko to keep reading indefinitely (i.e. to only stop when there is
+no new data), then you can set 'read_timeout=0'.
- def read_until_prompt_or_pattern(self, pattern="", re_flags=0):
- """Read until either self.base_prompt or pattern is detected.
+You can look at the Netmiko session_log or debug log for more information.
- :param pattern: the pattern used to identify that the output is complete (i.e. stop \
- reading when pattern is detected). pattern will be combined with self.base_prompt to \
- terminate output reading when the first of self.base_prompt or pattern is detected.
- :type pattern: regular expression string
+"""
+ raise ReadTimeout(msg)
+ return channel_data
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
+ def read_until_prompt(
+ self,
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel up to and including self.base_prompt."""
+ pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ pattern = f"{pattern}.*"
+ return self.read_until_pattern(
+ pattern=pattern,
+ re_flags=re_flags,
+ max_loops=max_loops,
+ read_timeout=read_timeout,
+ )
- """
- combined_pattern = re.escape(self.base_prompt)
+ def read_until_prompt_or_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read until either self.base_prompt or pattern is detected."""
+ prompt_pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ prompt_pattern = f"{prompt_pattern}.*"
if pattern:
- combined_pattern = r"({}|{})".format(combined_pattern, pattern)
- return self._read_channel_expect(combined_pattern, re_flags=re_flags)
+ combined_pattern = r"(?:{}|{})".format(prompt_pattern, pattern)
+ else:
+ combined_pattern = prompt_pattern
+ return self.read_until_pattern(
+ pattern=combined_pattern,
+ re_flags=re_flags,
+ max_loops=max_loops,
+ read_timeout=read_timeout,
+ )
def serial_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:[Uu]ser:|sername|ogin)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
- self.telnet_login(
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:[Uu]ser:|sername|ogin)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
+ return self.telnet_login(
pri_prompt_terminator,
alt_prompt_terminator,
username_pattern,
@@ -1407,33 +1531,28 @@
Classes
def telnet_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
- ):
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+ ) -> str:
"""Telnet login. Can be username/password or just password.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param username_pattern: Pattern used to identify the username prompt
- :type username_pattern: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
:param max_loops: Controls the wait time in conjunction with the delay_factor
- (default: 20)
"""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
+ # Revert telnet_login back to old speeds/delays
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -1459,6 +1578,7 @@
Classes
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -1478,6 +1598,7 @@
Classes
time.sleep(0.5 * delay_factor)
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -1493,10 +1614,11 @@
Classes
return return_msg
msg = f"Login failed: {self.host}"
+ assert self.remote_conn is not None
self.remote_conn.close()
raise NetmikoAuthenticationException(msg)
- def _try_session_preparation(self):
+ def _try_session_preparation(self) -> None:
"""
In case of an exception happening during `session_preparation()` Netmiko should
gracefully clean-up after itself. This might be challenging for library users
@@ -1509,7 +1631,7 @@
Classes
self.disconnect()
raise
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -1517,31 +1639,27 @@
Classes
early on in the session.
In general, it should include:
- self._test_channel_read()
+ self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
- self.disable_paging()
self.set_terminal_width()
- self.clear_buffer()
+ self.disable_paging()
"""
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
self.disable_paging()
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def _use_ssh_config(self, dict_arg):
+ def _use_ssh_config(self, dict_arg: Dict[str, Any]) -> Dict[str, Any]:
"""Update SSH connection parameters based on contents of SSH config file.
:param dict_arg: Dictionary of SSH connection parameters
- :type dict_arg: dict
"""
connect_dict = dict_arg.copy()
# Use SSHConfig to generate source content.
+ assert self.ssh_config_file is not None
full_path = path.abspath(path.expanduser(self.ssh_config_file))
+ source: Union[paramiko.config.SSHConfigDict, Dict[str, Any]]
if path.exists(full_path):
ssh_config_instance = paramiko.SSHConfig()
with io.open(full_path, "rt", encoding="utf-8") as f:
@@ -1551,6 +1669,7 @@
Classes
source = {}
# Keys get normalized to lower-case
+ proxy: Optional[paramiko.proxy.ProxyCommand]
if "proxycommand" in source:
proxy = paramiko.ProxyCommand(source["proxycommand"])
elif "proxyjump" in source:
@@ -1579,7 +1698,7 @@
msg += self.RETURN + str(auth_err)
raise NetmikoAuthenticationException(msg)
- except paramiko.ssh_exception.SSHException as no_session_err:
+ except paramiko.ssh_exception.SSHException as e:
self.paramiko_cleanup()
- if "No existing session" in str(no_session_err):
+ if "No existing session" in str(e):
msg = (
"Paramiko: 'No existing session' error: "
- "try increasing 'conn_timeout' to 10 seconds or larger."
+ "try increasing 'conn_timeout' to 15 seconds or larger."
)
raise NetmikoTimeoutException(msg)
else:
- raise
+ msg = f"""
+A paramiko SSHException occurred during connection creation:
+
+{str(e)}
+
+"""
+ raise NetmikoTimeoutException(msg)
if self.verbose:
print(f"SSH connection established to {self.host}:{self.port}")
@@ -1706,24 +1833,29 @@
Classes
self.remote_conn.settimeout(self.blocking_timeout)
if self.keepalive:
+ assert isinstance(self.remote_conn.transport, paramiko.Transport)
self.remote_conn.transport.set_keepalive(self.keepalive)
+
+ # Migrating communication to channel class
+ self.channel = SSHChannel(conn=self.remote_conn, encoding=self.encoding)
+
self.special_login_handler()
if self.verbose:
print("Interactive SSH session established")
- return ""
- # @m_exec_time
- def _test_channel_read(self, count=40, pattern=""):
+ return None
+
+ def _test_channel_read(self, count: int = 40, pattern: str = "") -> str:
"""Try to read the channel (generally post login) verify you receive data back.
:param count: the number of times to check the channel for data
- :type count: int
:param pattern: Regular expression pattern used to determine end of channel read
- :type pattern: str
"""
- def _increment_delay(main_delay, increment=1.1, maximum=8):
+ def _increment_delay(
+ main_delay: float, increment: float = 1.1, maximum: int = 8
+ ) -> float:
"""Increment sleep time to a maximum value."""
main_delay = main_delay * increment
if main_delay >= maximum:
@@ -1732,30 +1864,26 @@
Classes
i = 0
delay_factor = self.select_delay_factor(delay_factor=0)
+
+ if pattern:
+ return self.read_until_pattern(pattern=pattern, read_timeout=20)
+
main_delay = delay_factor * 0.1
time.sleep(main_delay * 10)
new_data = ""
while i <= count:
- new_data += self._read_channel_timing()
- if new_data and pattern:
- if re.search(pattern, new_data):
- break
- elif new_data:
- break
- else:
- self.write_channel(self.RETURN)
+ new_data += self.read_channel_timing()
+ if new_data:
+ return new_data
+ self.write_channel(self.RETURN)
main_delay = _increment_delay(main_delay)
time.sleep(main_delay)
i += 1
- # check if data was ever present
- if new_data:
- return new_data
- else:
- raise NetmikoTimeoutException("Timed out waiting for data")
+ raise NetmikoTimeoutException("Timed out waiting for data")
- def _build_ssh_client(self):
+ def _build_ssh_client(self) -> paramiko.SSHClient:
"""Prepare for Paramiko SSH connection."""
# Create instance of SSHClient object
remote_conn_pre = paramiko.SSHClient()
@@ -1770,7 +1898,7 @@
Classes
remote_conn_pre.set_missing_host_key_policy(self.key_policy)
return remote_conn_pre
- def select_delay_factor(self, delay_factor):
+ def select_delay_factor(self, delay_factor: float) -> float:
"""
Choose the greater of delay_factor or self.global_delay_factor (default).
In fast_cli choose the lesser of delay_factor of self.global_delay_factor.
@@ -1789,31 +1917,37 @@
Classes
else:
return self.global_delay_factor
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handler for devices like WLC, Extreme ERS that throw up characters prior to login."""
pass
def disable_paging(
- self, command="terminal length 0", delay_factor=1, cmd_verify=True, pattern=None
- ):
+ self,
+ command: str = "terminal length 0",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = True,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Disable paging default to a Cisco CLI method.
:param command: Device command to disable pagination of output
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
command = self.normalize_cmd(command)
log.debug("In disable_paging")
log.debug(f"Command: {command}")
self.write_channel(command)
# Make sure you read until you detect the command echo (avoid getting out of sync)
if cmd_verify and self.global_cmd_verify is not False:
- output = self.read_until_pattern(pattern=re.escape(command.strip()))
+ output = self.read_until_pattern(
+ pattern=re.escape(command.strip()), read_timeout=20
+ )
elif pattern:
- output = self.read_until_pattern(pattern=pattern)
+ output = self.read_until_pattern(pattern=pattern, read_timeout=20)
else:
output = self.read_until_prompt()
log.debug(f"{output}")
@@ -1821,24 +1955,29 @@
Classes
return output
def set_terminal_width(
- self, command="", delay_factor=1, cmd_verify=False, pattern=None
- ):
+ self,
+ command: str = "",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = False,
+ pattern: Optional[str] = None,
+ ) -> str:
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
if not command:
return ""
- delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
+
# Avoid cmd_verify here as terminal width must be set before doing cmd_verify
if cmd_verify and self.global_cmd_verify is not False:
output = self.read_until_pattern(pattern=re.escape(command.strip()))
@@ -1855,8 +1994,12 @@
entering/exiting config mode.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+
+ :param pattern: Regular expression pattern to search for in find_prompt() call
"""
- prompt = self.find_prompt(delay_factor=delay_factor)
+ if pattern is None:
+ if pri_prompt_terminator and alt_prompt_terminator:
+ pri_term = re.escape(pri_prompt_terminator)
+ alt_term = re.escape(alt_prompt_terminator)
+ pattern = rf"({pri_term}|{alt_term})"
+ elif pri_prompt_terminator:
+ pattern = re.escape(pri_prompt_terminator)
+ elif alt_prompt_terminator:
+ pattern = re.escape(alt_prompt_terminator)
+
+ if pattern:
+ prompt = self.find_prompt(delay_factor=delay_factor, pattern=pattern)
+ else:
+ prompt = self.find_prompt(delay_factor=delay_factor)
+
if not prompt[-1] in (pri_prompt_terminator, alt_prompt_terminator):
raise ValueError(f"Router prompt not found: {repr(prompt)}")
# Strip off trailing terminator
self.base_prompt = prompt[:-1]
return self.base_prompt
- def find_prompt(self, delay_factor=1):
+ def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+ ) -> str:
"""Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
+
+ :param pattern: Regular expression pattern to determine whether prompt is valid
"""
delay_factor = self.select_delay_factor(delay_factor)
+ sleep_time = delay_factor * 0.25
self.clear_buffer()
self.write_channel(self.RETURN)
- sleep_time = delay_factor * 0.1
- time.sleep(sleep_time)
-
- # Initial attempt to get prompt
- prompt = self.read_channel().strip()
- # Check if the only thing you received was a newline
- count = 0
- while count <= 12 and not prompt:
+ if pattern:
+ try:
+ prompt = self.read_until_pattern(pattern=pattern)
+ except ReadTimeout:
+ pass
+ else:
+ # Initial read
+ time.sleep(sleep_time)
prompt = self.read_channel().strip()
- if not prompt:
- self.write_channel(self.RETURN)
- time.sleep(sleep_time)
- if sleep_time <= 3:
- # Double the sleep_time when it is small
- sleep_time *= 2
- else:
- sleep_time += 1
- count += 1
+
+ count = 0
+ while count <= 12 and not prompt:
+ if not prompt:
+ self.write_channel(self.RETURN)
+ time.sleep(sleep_time)
+ prompt = self.read_channel().strip()
+ if sleep_time <= 3:
+ # Double the sleep_time when it is small
+ sleep_time *= 2
+ else:
+ sleep_time += 1
+ count += 1
# If multiple lines in the output take the last line
- prompt = self.normalize_linefeeds(prompt)
prompt = prompt.split(self.RESPONSE_RETURN)[-1]
prompt = prompt.strip()
+ self.clear_buffer()
if not prompt:
raise ValueError(f"Unable to find prompt: {prompt}")
- time.sleep(delay_factor * 0.1)
- self.clear_buffer()
log.debug(f"[find_prompt()]: prompt is {prompt}")
return prompt
- def clear_buffer(self, backoff=True):
+ def clear_buffer(
+ self,
+ backoff: bool = True,
+ backoff_max: float = 3.0,
+ delay_factor: Optional[float] = None,
+ ) -> str:
"""Read any data available in the channel."""
- sleep_time = 0.1 * self.global_delay_factor
+
+ if delay_factor is None:
+ delay_factor = self.global_delay_factor
+ sleep_time = 0.1 * delay_factor
+
+ output = ""
for _ in range(10):
time.sleep(sleep_time)
data = self.read_channel()
+ data = self.strip_ansi_escape_codes(data)
+ output += data
if not data:
break
# Double sleep time each time we detect data
log.debug("Clear buffer detects data in the channel")
if backoff:
sleep_time *= 2
- sleep_time = 3 if sleep_time >= 3 else sleep_time
+ sleep_time = backoff_max if sleep_time >= backoff_max else sleep_time
+ return output
- @select_cmd_verify
- 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,
- ):
+ def command_echo_read(self, cmd: str, read_timeout: float) -> str:
+
+ # Make sure you read until you detect the command echo (avoid getting out of sync)
+ new_data = self.read_until_pattern(
+ pattern=re.escape(cmd), read_timeout=read_timeout
+ )
+
+ # There can be echoed prompts that haven't been cleared before the cmd echo
+ # this can later mess up the trailing prompt pattern detection. Clear this out.
+ lines = new_data.split(cmd)
+ if len(lines) == 2:
+ # lines[-1] should realistically just be the null string
+ new_data = f"{cmd}{lines[-1]}"
+ else:
+ # cmd exists in the output multiple times? Just retain the original output
+ pass
+ return new_data
+
+ @select_cmd_verify
+ def send_command_timing(
+ self,
+ command_string: str,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = False,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type use_textfsm: 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).
- :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).
- :type cmd_verify: bool
-
- :param cmd_echo: Deprecated (use cmd_verify instead)
- :type cmd_echo: bool
"""
-
- # For compatibility; remove cmd_echo in Netmiko 4.x.x
- if cmd_echo is not None:
- cmd_verify = cmd_echo
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
output = ""
- delay_factor = self.select_delay_factor(delay_factor)
-
+ new_data = ""
if normalize:
command_string = self.normalize_cmd(command_string)
self.write_channel(command_string)
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
-
- # Strip off everything before the command echo
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- output = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
- else:
- # cmd is in the actual output (not just echoed)
- output = new_data
-
- log.debug(f"send_command_timing current output: {output}")
-
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
+ output += new_data
+ output += self.read_channel_timing(
+ last_read=last_read, read_timeout=read_timeout
)
+
output = self._sanitize_output(
output,
strip_command=strip_command,
command_string=command_string,
strip_prompt=strip_prompt,
)
+ return_data = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
+ )
+ return return_data
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
-
- log.debug(f"send_command_timing final output: {output}")
+ def _send_command_timing_str(self, *args: Any, **kwargs: Any) -> str:
+ """Wrapper for `send_command_timing` method that always returns a
+ string"""
+ output = self.send_command_timing(*args, **kwargs)
+ assert isinstance(output, str)
return output
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
:param a_string: Returned string from device
@@ -2075,12 +2228,13 @@
Classes
"""
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
+
if self.base_prompt in last_line:
return self.RESPONSE_RETURN.join(response_list[:-1])
else:
return a_string
- def _first_line_handler(self, data, search_pattern):
+ def _first_line_handler(self, data: str, search_pattern: str) -> Tuple[str, bool]:
"""
In certain situations the first line will get repainted which causes a false
match on the terminating pattern.
@@ -2107,126 +2261,151 @@
Classes
except IndexError:
return (data, False)
+ def _prompt_handler(self, auto_find_prompt: bool) -> str:
+ if auto_find_prompt:
+ try:
+ prompt = self.find_prompt()
+ except ValueError:
+ prompt = self.base_prompt
+ else:
+ prompt = self.base_prompt
+ return re.escape(prompt.strip())
+
@select_cmd_verify
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,
- ):
+ command_string: str,
+ expect_string: Optional[str] = None,
+ read_timeout: float = 10.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ auto_find_prompt: bool = True,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = True,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a pattern-based mechanism. Generally
used for show commands. By default this method will keep waiting to receive data until the
network device prompt is detected. The current network device prompt will be determined
automatically.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
:param expect_string: Regular expression pattern to use for determining end of output.
If left blank will default to being based on router prompt.
- :type expect_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type normalize: bool
: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).
- :type cmd_verify: bool
"""
# Time to delay in each read loop
- loop_delay = 0.2
+ loop_delay = 0.025
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 500:
- # Default arguments are being used; use self.timeout instead
- max_loops = int(self.timeout / loop_delay)
-
- # Find the current router prompt
- if expect_string is None:
- if auto_find_prompt:
- try:
- prompt = self.find_prompt(delay_factor=delay_factor)
- except ValueError:
- prompt = self.base_prompt
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ if self.delay_factor_compat:
+ # For compatibility calculate the old equivalent read_timeout
+ # i.e. what it would have been in Netmiko 3.x
+ if delay_factor is None:
+ tmp_delay_factor = self.global_delay_factor
else:
- prompt = self.base_prompt
- search_pattern = re.escape(prompt.strip())
+ tmp_delay_factor = self.select_delay_factor(delay_factor)
+ compat_timeout = calc_old_timeout(
+ max_loops=max_loops,
+ delay_factor=tmp_delay_factor,
+ loop_delay=0.2,
+ old_timeout=self.timeout,
+ )
+ msg = f"""\n
+You have chosen to use Netmiko's delay_factor compatibility mode for
+send_command. This will revert Netmiko to behave similarly to how it
+did in Netmiko 3.x (i.e. to use delay_factor/global_delay_factor and
+max_loops).
+
+Using these parameters Netmiko has calculated an effective read_timeout
+of {compat_timeout} and will set the read_timeout to this value.
+
+Please convert your code to that new format i.e.:
+
+ net_connect.send_command(cmd, read_timeout={compat_timeout})
+
+And then disable delay_factor_compat.
+
+delay_factor_compat will be removed in Netmiko 5.x.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ # Override the read_timeout with Netmiko 3.x way :-(
+ read_timeout = compat_timeout
+
else:
+ # No need for two deprecation messages so only display this if not using
+ # delay_factor_compat
+ if delay_factor is not None or max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of delay_factor/max_loops with
+send_command. You should convert all uses of delay_factor and max_loops
+over to read_timeout=x where x is the total number of seconds to wait
+before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if expect_string is not None:
search_pattern = expect_string
+ else:
+ search_pattern = self._prompt_handler(auto_find_prompt)
if normalize:
command_string = self.normalize_cmd(command_string)
- time.sleep(delay_factor * loop_delay)
- self.clear_buffer()
+ # Start the clock
+ start_time = time.time()
self.write_channel(command_string)
new_data = ""
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
- # Strip off everything before the command echo (to avoid false positives on the prompt)
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- new_data = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
- i = 1
+ MAX_CHARS = 2_000_000
+ DEQUE_SIZE = 20
output = ""
- past_three_reads = deque(maxlen=3)
+ # Check only the past N-reads. This is for the case where the output is
+ # very large (i.e. searching a very large string for a pattern a whole bunch of times)
+ past_n_reads: Deque[str] = deque(maxlen=DEQUE_SIZE)
first_line_processed = False
- # Keep reading data until search_pattern is found or until max_loops is reached.
- while i <= max_loops:
+ # Keep reading data until search_pattern is found or until read_timeout
+ while time.time() - start_time < read_timeout:
if new_data:
output += new_data
- past_three_reads.append(new_data)
+ past_n_reads.append(new_data)
# Case where we haven't processed the first_line yet (there is a potential issue
# in the first line (in cases where the line is repainted).
@@ -2239,19 +2418,30 @@
Classes
break
else:
- # Check if pattern is in the past three reads
- if re.search(search_pattern, "".join(past_three_reads)):
- break
+ if len(output) <= MAX_CHARS:
+ if re.search(search_pattern, output):
+ break
+ else:
+ # Switch to deque mode if output is greater than MAX_CHARS
+ # Check if pattern is in the past n reads
+ if re.search(search_pattern, "".join(past_n_reads)):
+ break
- time.sleep(delay_factor * loop_delay)
- i += 1
+ time.sleep(loop_delay)
new_data = self.read_channel()
+
else: # nobreak
- raise IOError(
- "Search pattern never detected in send_command: {}".format(
- search_pattern
- )
- )
+ msg = f"""
+Pattern not detected: {repr(search_pattern)} in output.
+
+Things you might try to fix this:
+1. Explicitly set your pattern using the expect_string argument.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.
+
+"""
+ raise ReadTimeout(msg)
output = self._sanitize_output(
output,
@@ -2259,45 +2449,98 @@
Classes
command_string=command_string,
strip_prompt=strip_prompt,
)
+ return_val = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
+ )
+ return return_val
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
+ def _send_command_str(self, *args: Any, **kwargs: Any) -> str:
+ """Wrapper for `send_command` method that always returns a string"""
+ output = self.send_command(*args, **kwargs)
+ assert isinstance(output, str)
return output
- def send_command_expect(self, *args, **kwargs):
- """Support previous name of send_command method.
+ def send_command_expect(
+ self, *args: Any, **kwargs: Any
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """Support previous name of send_command method."""
+ return self.send_command(*args, **kwargs)
- :param args: Positional arguments to send to send_command()
- :type args: list
+ def _multiline_kwargs(self, **kwargs: Any) -> Dict[str, Any]:
+ strip_prompt = kwargs.get("strip_prompt", False)
+ kwargs["strip_prompt"] = strip_prompt
+ strip_command = kwargs.get("strip_command", False)
+ kwargs["strip_command"] = strip_command
+ return kwargs
- :param kwargs: Keyword arguments to send to send_command()
- :type kwargs: dict
+ def send_multiline(
+ self,
+ commands: Sequence[Union[str, List[str]]],
+ multiline: bool = True,
+ **kwargs: Any,
+ ) -> str:
"""
- return self.send_command(*args, **kwargs)
+ commands should either be:
+
+ commands = [[cmd1, expect1], [cmd2, expect2], ...]]
+
+ Or
+
+ commands = [cmd1, cmd2, cmd3, ...]
+
+ Any expect_string that is a null-string will use pattern based on
+ device's prompt (unless expect_string argument is passed in via
+ kwargs.
+
+ """
+ output = ""
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+
+ default_expect_string = kwargs.pop("expect_string", None)
+ if not default_expect_string:
+ auto_find_prompt = kwargs.get("auto_find_prompt", True)
+ default_expect_string = self._prompt_handler(auto_find_prompt)
+
+ if commands and isinstance(commands[0], str):
+ # If list of commands just send directly using default_expect_string (probably prompt)
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_str(
+ cmd, expect_string=default_expect_string, **kwargs
+ )
+ else:
+ # If list of lists, then first element is cmd and second element is expect_string
+ for cmd_item in commands:
+ assert not isinstance(cmd_item, str)
+ cmd, expect_string = cmd_item
+ if not expect_string:
+ expect_string = default_expect_string
+ output += self._send_command_str(
+ cmd, expect_string=expect_string, **kwargs
+ )
+ return output
+
+ def send_multiline_timing(
+ self, commands: Sequence[str], multiline: bool = True, **kwargs: Any
+ ) -> str:
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+ output = ""
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_timing_str(cmd, **kwargs)
+ return output
@staticmethod
- def strip_backspaces(output):
+ def strip_backspaces(output: str) -> str:
"""Strip any backspace characters out of the output.
:param output: Output obtained from a remote network device.
@@ -2306,7 +2549,7 @@
# command_string isn't there; do nothing
return output
- def normalize_linefeeds(self, a_string):
+ def normalize_linefeeds(self, a_string: str) -> str:
"""Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
:param a_string: A string that may have non-normalized line feeds
@@ -2350,7 +2593,7 @@
Classes
else:
return a_string
- def normalize_cmd(self, command):
+ def normalize_cmd(self, command: str) -> str:
"""Normalize CLI commands to have a single trailing newline.
:param command: Command that may require line feed to be normalized
@@ -2360,32 +2603,32 @@
Classes
command += self.RETURN
return command
- def check_enable_mode(self, check_string=""):
+ def check_enable_mode(self, check_string: str = "") -> bool:
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
"""
self.write_channel(self.RETURN)
- output = self.read_until_prompt()
+ output = self.read_until_prompt(read_entire_line=True)
return check_string in output
def enable(
- self, cmd="", pattern="ssword", enable_pattern=None, re_flags=re.IGNORECASE
- ):
+ self,
+ cmd: str = "",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
"""Enter enable mode.
:param cmd: Device command to enter enable mode
- :type cmd: str
:param pattern: pattern to search for indicating device is waiting for password
- :type pattern: str
:param enable_pattern: pattern indicating you have entered enable mode
- :type pattern: str
:param re_flags: Regular expression flags used in conjunction with pattern
- :type re_flags: int
"""
output = ""
msg = (
@@ -2424,7 +2667,7 @@
Automatically exits/enters configuration mode.
:param config_commands: Multiple configuration commands to be sent to the device
- :type config_commands: list or string
:param exit_config_mode: Determines whether or not to exit config mode after complete
- :type exit_config_mode: bool
- :param delay_factor: Factor to adjust delays
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor (default: 150)
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Determines whether or not to strip the prompt
- :type strip_prompt: bool
:param strip_command: Determines whether or not to strip the command
- :type strip_command: bool
+
+ :param read_timeout: Absolute timer to send to read_channel_timing. Should be rarely needed.
:param config_mode_command: The command to enter into config mode
- :type config_mode_command: str
:param cmd_verify: Whether or not to verify command echo for each command in config_set
- :type cmd_verify: bool
:param enter_config_mode: Do you enter config mode before sending config commands
- :type exit_config_mode: bool
:param error_pattern: Regular expression pattern to detect config errors in the
output.
- :type error_pattern: str
+
+ :param terminator: Regular expression pattern to use as an alternate terminator in certain
+ situations.
+
+ :param bypass_commands: Regular expression pattern indicating configuration commands
+ where cmd_verify is automatically disabled.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if self.global_cmd_verify is not None:
+ cmd_verify = self.global_cmd_verify
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ # Calculate an equivalent read_timeout (if using old settings)
+ # Eliminate in Netmiko 5.x
+ if read_timeout is None:
+ max_loops = 150 if max_loops is None else max_loops
+ delay_factor = 1.0 if delay_factor is None else delay_factor
+
+ # If delay_factor has been set, then look at global_delay_factor
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ read_timeout = calc_old_timeout(
+ max_loops=max_loops, delay_factor=delay_factor, loop_delay=0.1
+ )
+
+ if delay_factor is None:
+ delay_factor = self.select_delay_factor(0)
+ else:
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ if read_timeout is None:
+ read_timeout = 15
+ else:
+ read_timeout = read_timeout
+
if config_commands is None:
return ""
elif isinstance(config_commands, str):
@@ -2584,20 +2865,33 @@
Classes
if not hasattr(config_commands, "__iter__"):
raise ValueError("Invalid argument passed into send_config_set")
+ if bypass_commands is None:
+ # Commands where cmd_verify is automatically disabled reg-ex logical-or
+ bypass_commands = r"^banner .*$"
+
+ # Set bypass_commands="" to force no-bypass (usually for testing)
+ bypass_detected = False
+ if bypass_commands:
+ bypass_detected = any(
+ [True for cmd in config_commands if re.search(bypass_commands, cmd)]
+ )
+ if bypass_detected:
+ cmd_verify = False
+
# Send config commands
output = ""
if enter_config_mode:
- cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
- output += self.config_mode(*cfg_mode_args)
+ if config_mode_command:
+ output += self.config_mode(config_mode_command)
+ else:
+ output += self.config_mode()
- # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ # Perform output gathering line-by-line (legacy way)
if self.fast_cli and self._legacy_mode and not error_pattern:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
elif not cmd_verify:
for cmd in config_commands:
@@ -2606,35 +2900,25 @@
Classes
# Gather the output incrementally due to error_pattern requirements
if error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
if re.search(error_pattern, output, flags=re.M):
msg = f"Invalid input detected at command: {cmd}"
raise ConfigInvalidException(msg)
# Standard output gathering (no error_pattern)
if not error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Make sure command is echoed
- new_output = self.read_until_pattern(pattern=re.escape(cmd.strip()))
- output += new_output
-
- # We might capture next prompt in the original read
- pattern = f"(?:{re.escape(self.base_prompt)}|#)"
- if not re.search(pattern, new_output):
- # Make sure trailing prompt comes back (after command)
- # NX-OS has fast-buffering problem where it immediately echoes command
- # Even though the device hasn't caught up with processing command.
- new_output = self.read_until_pattern(pattern=pattern)
- output += new_output
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+
+ # Read until next prompt or terminator (#); the .*$ forces read of entire line
+ pattern = f"(?:{re.escape(self.base_prompt)}.*$|{terminator}.*$)"
+ output += self.read_until_pattern(pattern=pattern, re_flags=re.M)
if error_pattern:
if re.search(error_pattern, output, flags=re.M):
@@ -2647,7 +2931,7 @@
Classes
log.debug(f"{output}")
return output
- def strip_ansi_escape_codes(self, string_buffer):
+ def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Remove any ANSI (VT100) ESC codes from the output
@@ -2668,10 +2952,11 @@
Classes
ESC[?6l Reset mode screen with options 640 x 200 monochrome (graphics)
ESC[?7l Disable line wrapping
ESC[2J Code erase display
- ESC[00;32m Color Green (30 to 37 are different colors) more general pattern is
- ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+ ESC[00;32m Color Green (30 to 37 are different colors)
ESC[6n Get cursor position
ESC[1D Move cursor position leftward by x characters (1 in this case)
+ ESC[9999B Move cursor down N-lines (very large value is attempt to move to the
+ very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
@@ -2693,7 +2978,8 @@
return output
- def cleanup(self, command=""):
+ def cleanup(self, command: str = "") -> None:
"""Logout of the session on the network device plus any additional cleanup."""
pass
- def paramiko_cleanup(self):
+ def paramiko_cleanup(self) -> None:
"""Cleanup Paramiko to try to gracefully handle SSH session ending."""
- self.remote_conn_pre.close()
+ if self.remote_conn_pre is not None:
+ self.remote_conn_pre.close()
del self.remote_conn_pre
- def disconnect(self):
+ def disconnect(self) -> None:
"""Try to gracefully close the session."""
try:
self.cleanup()
if self.protocol == "ssh":
self.paramiko_cleanup()
elif self.protocol == "telnet":
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
self.remote_conn.close()
elif self.protocol == "serial":
+ assert isinstance(self.remote_conn, serial.Serial)
self.remote_conn.close()
except Exception:
# There have been race conditions observed on disconnect.
@@ -2769,31 +3069,25 @@
Classes
finally:
self.remote_conn_pre = None
self.remote_conn = None
- self.close_session_log()
+ if self.session_log:
+ self.session_log.close()
- def commit(self):
+ def commit(self) -> str:
"""Commit method for platforms that support this."""
raise AttributeError("Network device does not support 'commit()' method")
- def save_config(self, *args, **kwargs):
+ def save_config(
+ self, cmd: str = "", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Not Implemented"""
raise NotImplementedError
- def open_session_log(self, filename, mode="write"):
- """Open the session_log file."""
- if mode == "append":
- self.session_log = open(filename, mode="a", encoding=self.encoding)
- else:
- self.session_log = open(filename, mode="w", encoding=self.encoding)
- self._session_log_close = True
-
- def close_session_log(self):
- """Close the session_log file (if it is a file that we opened)."""
- if self.session_log is not None and self._session_log_close:
- self.session_log.close()
- self.session_log = None
-
- def run_ttp(self, template, res_kwargs={}, **kwargs):
+ def run_ttp(
+ self,
+ template: Union[str, bytes, "PathLike[Any]"],
+ res_kwargs: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+ ) -> Any:
"""
Run TTP template parsing by using input parameters to collect
devices output.
@@ -2801,29 +3095,25 @@
Classes
:param template: template content, OS path to template or reference
to template within TTP templates collection in
ttp://path/to/template.txt format
- :type template: str
:param res_kwargs: ``**res_kwargs`` arguments to pass to TTP result method
- :type res_kwargs: dict
:param kwargs: any other ``**kwargs`` to use for TTP object instantiation
- :type kwargs: dict
TTP template must have inputs defined together with below parameters.
:param method: name of Netmiko connection object method to call, default ``send_command``
- :type method: str
:param kwargs: Netmiko connection object method arguments
- :type kwargs: dict
:param commands: list of commands to collect
- :type commands: list
Inputs' load could be of one of the supported formats and controlled by input's ``load``
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
"""
+ if res_kwargs is None:
+ res_kwargs = {}
return run_ttp_template(
connection=self, template=template, res_kwargs=res_kwargs, **kwargs
)
@@ -2863,7 +3153,7 @@
Static methods
Source code
@staticmethod
-def strip_backspaces(output):
+def strip_backspaces(output: str) -> str:
"""Strip any backspace characters out of the output.
:param output: Output obtained from a remote network device.
@@ -2887,7 +3177,7 @@
def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not.
:param check_string: Identification of configuration mode from the device
@@ -2899,7 +3189,7 @@
Methods
self.write_channel(self.RETURN)
# You can encounter an issue here (on router name changes) prefer delay-based solution
if not pattern:
- output = self._read_channel_timing()
+ output = self.read_channel_timing()
else:
output = self.read_until_pattern(pattern=pattern)
return check_string in output
@@ -2914,14 +3204,14 @@
Methods
:type check_string: str
Source code
-
def check_enable_mode(self, check_string=""):
+
def check_enable_mode(self, check_string: str = "") -> bool:
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
"""
self.write_channel(self.RETURN)
- output = self.read_until_prompt()
+ output = self.read_until_prompt(read_entire_line=True)
return check_string in output
@@ -2932,45 +3222,70 @@
Methods
Logout of the session on the network device plus any additional cleanup.
Source code
-
def cleanup(self, command=""):
+
def cleanup(self, command: str = "") -> None:
"""Logout of the session on the network device plus any additional cleanup."""
pass
def clear_buffer(
+ self,
+ backoff: bool = True,
+ backoff_max: float = 3.0,
+ delay_factor: Optional[float] = None,
+) -> str:
"""Read any data available in the channel."""
- sleep_time = 0.1 * self.global_delay_factor
+
+ if delay_factor is None:
+ delay_factor = self.global_delay_factor
+ sleep_time = 0.1 * delay_factor
+
+ output = ""
for _ in range(10):
time.sleep(sleep_time)
data = self.read_channel()
+ data = self.strip_ansi_escape_codes(data)
+ output += data
if not data:
break
# Double sleep time each time we detect data
log.debug("Clear buffer detects data in the channel")
if backoff:
sleep_time *= 2
- sleep_time = 3 if sleep_time >= 3 else sleep_time
Close the session_log file (if it is a file that we opened).
+
Source code
-
def close_session_log(self):
- """Close the session_log file (if it is a file that we opened)."""
- if self.session_log is not None and self._session_log_close:
- self.session_log.close()
- self.session_log = None
+
def command_echo_read(self, cmd: str, read_timeout: float) -> str:
+
+ # Make sure you read until you detect the command echo (avoid getting out of sync)
+ new_data = self.read_until_pattern(
+ pattern=re.escape(cmd), read_timeout=read_timeout
+ )
+
+ # There can be echoed prompts that haven't been cleared before the cmd echo
+ # this can later mess up the trailing prompt pattern detection. Clear this out.
+ lines = new_data.split(cmd)
+ if len(lines) == 2:
+ # lines[-1] should realistically just be the null string
+ new_data = f"{cmd}{lines[-1]}"
+ else:
+ # cmd exists in the output multiple times? Just retain the original output
+ pass
+ return new_data
@@ -2980,7 +3295,7 @@
Methods
Commit method for platforms that support this.
Source code
-
def commit(self):
+
def commit(self) -> str:
"""Commit method for platforms that support this."""
raise AttributeError("Network device does not support 'commit()' method")
def config_mode(
+ self, config_command: str = "", pattern: str = "", re_flags: int = 0
+) -> str:
"""Enter into config_mode.
:param config_command: Configuration command to send to the device
@@ -3018,45 +3335,51 @@
Methods
output += self.read_until_pattern(
pattern=re.escape(config_command.strip())
)
- if not re.search(pattern, output, flags=re_flags):
+ if pattern:
output += self.read_until_pattern(pattern=pattern, re_flags=re_flags)
+ else:
+ output += self.read_until_prompt(read_entire_line=True)
if not self.check_config_mode():
raise ValueError("Failed to enter configuration mode.")
return output
def establish_connection(self, width: int = 511, height: int = 1000) -> None:
"""Establish SSH connection to the network device
Timeout will generate a NetmikoTimeoutException
@@ -3185,16 +3507,21 @@
Finds the current network device prompt, last line only.
:param delay_factor: See init: global_delay_factor
-:type delay_factor: int
+:type delay_factor: int
+
:param pattern: Regular expression pattern to determine whether prompt is valid
Source code
-
def find_prompt(self, delay_factor=1):
+
def find_prompt(
+ self, delay_factor: float = 1.0, pattern: Optional[str] = None
+) -> str:
"""Finds the current network device prompt, last line only.
:param delay_factor: See __init__: global_delay_factor
:type delay_factor: int
+
+ :param pattern: Regular expression pattern to determine whether prompt is valid
"""
delay_factor = self.select_delay_factor(delay_factor)
+ sleep_time = delay_factor * 0.25
self.clear_buffer()
self.write_channel(self.RETURN)
- sleep_time = delay_factor * 0.1
- time.sleep(sleep_time)
-
- # Initial attempt to get prompt
- prompt = self.read_channel().strip()
- # Check if the only thing you received was a newline
- count = 0
- while count <= 12 and not prompt:
+ if pattern:
+ try:
+ prompt = self.read_until_pattern(pattern=pattern)
+ except ReadTimeout:
+ pass
+ else:
+ # Initial read
+ time.sleep(sleep_time)
prompt = self.read_channel().strip()
- if not prompt:
- self.write_channel(self.RETURN)
- time.sleep(sleep_time)
- if sleep_time <= 3:
- # Double the sleep_time when it is small
- sleep_time *= 2
- else:
- sleep_time += 1
- count += 1
+
+ count = 0
+ while count <= 12 and not prompt:
+ if not prompt:
+ self.write_channel(self.RETURN)
+ time.sleep(sleep_time)
+ prompt = self.read_channel().strip()
+ if sleep_time <= 3:
+ # Double the sleep_time when it is small
+ sleep_time *= 2
+ else:
+ sleep_time += 1
+ count += 1
# If multiple lines in the output take the last line
- prompt = self.normalize_linefeeds(prompt)
prompt = prompt.split(self.RESPONSE_RETURN)[-1]
prompt = prompt.strip()
+ self.clear_buffer()
if not prompt:
raise ValueError(f"Unable to find prompt: {prompt}")
- time.sleep(delay_factor * 0.1)
- self.clear_buffer()
log.debug(f"[find_prompt()]: prompt is {prompt}")
return prompt
@@ -3382,7 +3731,7 @@
Methods
Returns a boolean flag with the state of the connection.
Source code
-
def is_alive(self):
+
def is_alive(self) -> bool:
"""Returns a boolean flag with the state of the connection."""
null = chr(0)
if self.remote_conn is None:
@@ -3394,9 +3743,11 @@
Methods
# IAC = Interpret as Command; it comes before the NOP.
log.debug("Sending IAC + NOP")
# Need to send multiple times to test connection
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
- self.remote_conn.sock.sendall(telnetlib.IAC + telnetlib.NOP)
+ assert isinstance(self.remote_conn, telnetlib.Telnet)
+ telnet_socket = self.remote_conn.get_socket()
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
+ telnet_socket.sendall(telnetlib.IAC + telnetlib.NOP)
return True
except AttributeError:
return False
@@ -3406,7 +3757,11 @@
Methods
# Try sending ASCII null byte to maintain the connection alive
log.debug("Sending the NULL byte")
self.write_channel(null)
- return self.remote_conn.transport.is_active()
+ assert isinstance(self.remote_conn, paramiko.Channel)
+ assert self.remote_conn.transport is not None
+ result = self.remote_conn.transport.is_active()
+ assert isinstance(result, bool)
+ return result
except (socket.error, EOFError):
log.error("Unable to send", exc_info=True)
# If unable to send, we can tell for sure that the connection is unusable
@@ -3423,7 +3778,7 @@
Methods
:type command: str
Source code
-
def normalize_cmd(self, command):
+
def normalize_cmd(self, command: str) -> str:
"""Normalize CLI commands to have a single trailing newline.
:param command: Command that may require line feed to be normalized
@@ -3449,7 +3804,7 @@
Methods
Source code
-
def normalize_linefeeds(self, a_string):
+
def normalize_linefeeds(self, a_string: str) -> str:
"""Convert `\r\r\n`,`\r\n`, `\n\r` to `\n.`
:param a_string: A string that may have non-normalized line feeds
@@ -3465,22 +3820,6 @@
Cleanup Paramiko to try to gracefully handle SSH session ending.
Source code
-
def paramiko_cleanup(self):
+
def paramiko_cleanup(self) -> None:
"""Cleanup Paramiko to try to gracefully handle SSH session ending."""
- self.remote_conn_pre.close()
+ if self.remote_conn_pre is not None:
+ self.remote_conn_pre.close()
del self.remote_conn_pre
@@ -3498,105 +3838,295 @@
Methods
def read_channel(self)
-
Generic handler that will read all the data from an SSH or telnet channel.
+
Generic handler that will read all the data from given channel.
Source code
-
def read_channel(self):
- """Generic handler that will read all the data from an SSH or telnet channel."""
- output = ""
- self._lock_netmiko_session()
- try:
- output = self._read_channel()
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+
@lock_channel
+def read_channel(self) -> str:
+ """Generic handler that will read all the data from given channel."""
+ new_data = self.channel.read_channel()
+ new_data = self.normalize_linefeeds(new_data)
+ if self.ansi_escape_codes:
+ new_data = self.strip_ansi_escape_codes(new_data)
+ log.debug(f"read_channel: {new_data}")
+ if self.session_log:
+ self.session_log.write(new_data)
+
+ # If data had been previously saved to the buffer, the prepend it to output
+ # do post read_channel so session_log/log doesn't record buffered data twice
+ if self._read_buffer:
+ output = self._read_buffer + new_data
+ self._read_buffer = ""
+ else:
+ output = new_data
return output
General pattern is keep reading until no new data is read.
+Once no new data is read wait last_read amount of time (one last read).
+As long as no new data, then return data.
+
read_timeout is an absolute timer for how long to keep reading (which presupposes
+we are still getting new data).
+
Setting read_timeout to zero will cause read_channel_timing to never expire based
+on an absolute timeout. It will only complete based on timeout based on their being
+no new data.
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
+Source code
+
def read_channel_timing(
+ self,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read data on the channel based on timing delays.
+
+ General pattern is keep reading until no new data is read.
+ Once no new data is read wait `last_read` amount of time (one last read).
+ As long as no new data, then return data.
+
+ `read_timeout` is an absolute timer for how long to keep reading (which presupposes
+ we are still getting new data).
+
+ Setting `read_timeout` to zero will cause read_channel_timing to never expire based
+ on an absolute timeout. It will only complete based on timeout based on their being
+ no new data.
+
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ # Time to delay in each read loop
+ loop_delay = 0.1
+ channel_data = ""
+ start_time = time.time()
+
+ # Set read_timeout to 0 to never timeout
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ time.sleep(loop_delay)
+ new_data = self.read_channel()
+ # gather new output
+ if new_data:
+ channel_data += new_data
+ # if we have some output, but nothing new, then do the last read
+ elif channel_data != "":
+ # Make sure really done (i.e. no new data)
+ time.sleep(last_read)
+ new_data = self.read_channel()
+ if not new_data:
+ break
+ else:
+ channel_data += new_data
+ else:
+ msg = f"""\n
+read_channel_timing's absolute timer expired.
+
+The network device was continually outputting data for longer than {read_timeout}
+seconds.
+
+If this is expected i.e. the command you are executing is continually emitting
+data for a long period of time, then you can set 'read_timeout=x' seconds. If
+you want Netmiko to keep reading indefinitely (i.e. to only stop when there is
+no new data), then you can set 'read_timeout=0'.
+
+You can look at the Netmiko session_log or debug log for more information.
+
+"""
+ raise ReadTimeout(msg)
+ return channel_data
Read channel until pattern detected. Return ALL data available.
+
Read channel until pattern is detected.
+
Will return string up to and including pattern.
+
Returns ReadTimeout if pattern not detected in read_timeout seconds.
+
:param pattern: Regular expression pattern used to identify that reading is done.
+
:param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+reading indefinitely until pattern is detected.
+
:param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
Source code
-
def read_until_pattern(self, *args, **kwargs):
- """Read channel until pattern detected. Return ALL data available."""
- return self._read_channel_expect(*args, **kwargs)
+
def read_until_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+ ) -> str:
+ """Read channel until pattern is detected.
+
+ Will return string up to and including pattern.
+
+ Returns ReadTimeout if pattern not detected in read_timeout seconds.
+
+ :param pattern: Regular expression pattern used to identify that reading is done.
+
+ :param read_timeout: maximum time to wait looking for pattern. Will raise ReadTimeout.
+ A read_timeout value of 0 will cause the loop to never timeout (i.e. it will keep
+ reading indefinitely until pattern is detected.
+
+ :param re_flags: regex flags used in conjunction with pattern (defaults to no flags).
+
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+ """
+ if max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of max_loops with read_until_pattern.
+You should convert all uses of max_loops over to read_timeout=x
+where x is the total number of seconds to wait before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ output = ""
+ loop_delay = 0.01
+ start_time = time.time()
+ # if read_timeout == 0 or 0.0 keep reading indefinitely
+ while (time.time() - start_time < read_timeout) or (not read_timeout):
+ output += self.read_channel()
+ if re.search(pattern, output, flags=re_flags):
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ # The string matched by pattern must be retained in the output string.
+ # re.split will do this if capturing parentesis are used.
+ if len(results) == 2:
+ # no capturing parenthesis, convert and try again.
+ pattern = f"({pattern})"
+ results = re.split(pattern, output, maxsplit=1, flags=re_flags)
+
+ if len(results) != 3:
+ # well, we tried
+ msg = f"""Unable to successfully split output based on pattern:
+pattern={pattern}
+output={repr(output)}
+results={results}
+"""
+ raise ReadException(msg)
+
+ # Process such that everything before and including pattern is return.
+ # Everything else is retained in the _read_buffer
+ output, match_str, buffer = results
+ output = output + match_str
+ if buffer:
+ self._read_buffer += buffer
+ log.debug(f"Pattern found: {pattern} {output}")
+ return output
+ time.sleep(loop_delay)
+
+ msg = f"""\n\nPattern not detected: {repr(pattern)} in output.
+
+Things you might try to fix this:
+1. Adjust the regex pattern to better identify the terminating string. Note, in
+many situations the pattern is automatically based on the network device's prompt.
+2. Increase the read_timeout to a larger value.
+
+You can also look at the Netmiko session_log or debug log for more information.\n\n"""
+ raise ReadTimeout(msg)
Read until either self.base_prompt or pattern is detected.
-
:param pattern: the pattern used to identify that the output is complete (i.e. stop
-reading when pattern is detected). pattern will be combined with self.base_prompt to
-terminate output reading when the first of self.base_prompt or pattern is detected.
-:type pattern: regular expression string
-
:param re_flags: regex flags used in conjunction with pattern to search for prompt
-(defaults to no flags)
-:type re_flags: int
+
Read until either self.base_prompt or pattern is detected.
Source code
-
def read_until_prompt_or_pattern(self, pattern="", re_flags=0):
- """Read until either self.base_prompt or pattern is detected.
-
- :param pattern: the pattern used to identify that the output is complete (i.e. stop \
- reading when pattern is detected). pattern will be combined with self.base_prompt to \
- terminate output reading when the first of self.base_prompt or pattern is detected.
- :type pattern: regular expression string
-
- :param re_flags: regex flags used in conjunction with pattern to search for prompt \
- (defaults to no flags)
- :type re_flags: int
-
- """
- combined_pattern = re.escape(self.base_prompt)
+
def read_until_prompt_or_pattern(
+ self,
+ pattern: str = "",
+ read_timeout: float = 10.0,
+ read_entire_line: bool = False,
+ re_flags: int = 0,
+ max_loops: Optional[int] = None,
+) -> str:
+ """Read until either self.base_prompt or pattern is detected."""
+ prompt_pattern = re.escape(self.base_prompt)
+ if read_entire_line:
+ prompt_pattern = f"{prompt_pattern}.*"
if pattern:
- combined_pattern = r"({}|{})".format(combined_pattern, pattern)
- return self._read_channel_expect(combined_pattern, re_flags=re_flags)
Run TTP template parsing by using input parameters to collect
devices output.
:param template: template content, OS path to template or reference
to template within TTP templates collection in
-ttp://path/to/template.txt format
-:type template: str
-
:param res_kwargs: **res_kwargs arguments to pass to TTP result method
-:type res_kwargs: dict
-
:param kwargs: any other **kwargs to use for TTP object instantiation
-:type kwargs: dict
+ttp://path/to/template.txt format
+
:param res_kwargs: **res_kwargs arguments to pass to TTP result method
+
:param kwargs: any other **kwargs to use for TTP object instantiation
TTP template must have inputs defined together with below parameters.
-
:param method: name of Netmiko connection object method to call, default send_command
-:type method: str
Inputs' load could be of one of the supported formats and controlled by input's load
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
def run_ttp(
+ self,
+ template: Union[str, bytes, "PathLike[Any]"],
+ res_kwargs: Optional[Dict[str, Any]] = None,
+ **kwargs: Any,
+) -> Any:
"""
Run TTP template parsing by using input parameters to collect
devices output.
@@ -3604,42 +4134,40 @@
Methods
:param template: template content, OS path to template or reference
to template within TTP templates collection in
ttp://path/to/template.txt format
- :type template: str
:param res_kwargs: ``**res_kwargs`` arguments to pass to TTP result method
- :type res_kwargs: dict
:param kwargs: any other ``**kwargs`` to use for TTP object instantiation
- :type kwargs: dict
TTP template must have inputs defined together with below parameters.
:param method: name of Netmiko connection object method to call, default ``send_command``
- :type method: str
:param kwargs: Netmiko connection object method arguments
- :type kwargs: dict
:param commands: list of commands to collect
- :type commands: list
Inputs' load could be of one of the supported formats and controlled by input's ``load``
attribute, supported values - python, yaml or json. For each input output collected
from device and parsed accordingly.
"""
+ if res_kwargs is None:
+ res_kwargs = {}
return run_ttp_template(
connection=self, template=template, res_kwargs=res_kwargs, **kwargs
)
def select_delay_factor(self, delay_factor: float) -> float:
"""
Choose the greater of delay_factor or self.global_delay_factor (default).
In fast_cli choose the lesser of delay_factor of self.global_delay_factor.
@@ -3675,429 +4203,356 @@
Execute command_string on the SSH channel using a pattern-based mechanism. Generally
used for show commands. By default this method will keep waiting to receive data until the
network device prompt is detected. The current network device prompt will be determined
automatically.
-
:param command_string: The command to be executed on the remote device.
-:type command_string: str
+
:param command_string: The command to be executed on the remote device.
:param expect_string: Regular expression pattern to use for determining end of output.
-If left blank will default to being based on router prompt.
-:type expect_string: str
-
:param delay_factor: Multiplying factor used to adjust delays (default: 1).
-:type delay_factor: int
-
:param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
-based upon self.timeout.
-:type max_loops: int
-
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
-:type strip_prompt: bool
-
:param strip_command: Remove the echo of the command from the output (default: True).
-:type strip_command: bool
-
:param normalize: Ensure the proper enter is sent at end of command (default: True).
-:type normalize: bool
-
:param use_textfsm: Process command output through TextFSM template (default: False).
-:type normalize: bool
+If left blank will default to being based on router prompt.
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
+
:param strip_command: Remove the echo of the command from the output (default: True).
+
:param normalize: Ensure the proper enter is sent at end of command (default: True).
+
:param use_textfsm: Process command output through TextFSM template (default: False).
: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 use_ttp: Process command output through TTP template (default: False).
: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
+path, relative path, or name of file in current directory. (default: None).
+
:param use_genie: Process command output through PyATS/Genie parser (default: False).
+
:param cmd_verify: Verify command echo before proceeding (default: True).
Source code
-
@select_cmd_verify
-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
- used for show commands. By default this method will keep waiting to receive data until the
- network device prompt is detected. The current network device prompt will be determined
- automatically.
+
@select_cmd_verify
+ def send_command(
+ self,
+ command_string: str,
+ expect_string: Optional[str] = None,
+ read_timeout: float = 10.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ auto_find_prompt: bool = True,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = True,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """Execute command_string on the SSH channel using a pattern-based mechanism. Generally
+ used for show commands. By default this method will keep waiting to receive data until the
+ network device prompt is detected. The current network device prompt will be determined
+ automatically.
- :param command_string: The command to be executed on the remote device.
- :type command_string: str
+ :param command_string: The command to be executed on the remote device.
- :param expect_string: Regular expression pattern to use for determining end of output.
- If left blank will default to being based on router prompt.
- :type expect_string: str
+ :param expect_string: Regular expression pattern to use for determining end of output.
+ If left blank will default to being based on router prompt.
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
+ :param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
+ :param strip_command: Remove the echo of the command from the output (default: True).
- :param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
+ :param normalize: Ensure the proper enter is sent at end of command (default: True).
- :param use_textfsm: Process command output through TextFSM template (default: False).
- :type normalize: bool
+ :param use_textfsm: Process command output through TextFSM template (default: False).
- :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 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 use_ttp: Process command output through TTP template (default: False).
- :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 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).
- :param use_genie: Process command output through PyATS/Genie parser (default: False).
- :type normalize: bool
+ :param use_genie: Process command output through PyATS/Genie parser (default: False).
- :param cmd_verify: Verify command echo before proceeding (default: True).
- :type cmd_verify: bool
- """
+ :param cmd_verify: Verify command echo before proceeding (default: True).
+ """
- # Time to delay in each read loop
- loop_delay = 0.2
+ # Time to delay in each read loop
+ loop_delay = 0.025
- # Default to making loop time be roughly equivalent to self.timeout (support old max_loops
- # and delay_factor arguments for backwards compatibility).
- delay_factor = self.select_delay_factor(delay_factor)
- if delay_factor == 1 and max_loops == 500:
- # Default arguments are being used; use self.timeout instead
- max_loops = int(self.timeout / loop_delay)
+ if self.read_timeout_override:
+ read_timeout = self.read_timeout_override
+
+ if self.delay_factor_compat:
+ # For compatibility calculate the old equivalent read_timeout
+ # i.e. what it would have been in Netmiko 3.x
+ if delay_factor is None:
+ tmp_delay_factor = self.global_delay_factor
+ else:
+ tmp_delay_factor = self.select_delay_factor(delay_factor)
+ compat_timeout = calc_old_timeout(
+ max_loops=max_loops,
+ delay_factor=tmp_delay_factor,
+ loop_delay=0.2,
+ old_timeout=self.timeout,
+ )
+ msg = f"""\n
+You have chosen to use Netmiko's delay_factor compatibility mode for
+send_command. This will revert Netmiko to behave similarly to how it
+did in Netmiko 3.x (i.e. to use delay_factor/global_delay_factor and
+max_loops).
+
+Using these parameters Netmiko has calculated an effective read_timeout
+of {compat_timeout} and will set the read_timeout to this value.
+
+Please convert your code to that new format i.e.:
+
+ net_connect.send_command(cmd, read_timeout={compat_timeout})
+
+And then disable delay_factor_compat.
+
+delay_factor_compat will be removed in Netmiko 5.x.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ # Override the read_timeout with Netmiko 3.x way :-(
+ read_timeout = compat_timeout
- # Find the current router prompt
- if expect_string is None:
- if auto_find_prompt:
- try:
- prompt = self.find_prompt(delay_factor=delay_factor)
- except ValueError:
- prompt = self.base_prompt
else:
- prompt = self.base_prompt
- search_pattern = re.escape(prompt.strip())
- else:
- search_pattern = expect_string
+ # No need for two deprecation messages so only display this if not using
+ # delay_factor_compat
+ if delay_factor is not None or max_loops is not None:
+ msg = """\n
+Netmiko 4.x has deprecated the use of delay_factor/max_loops with
+send_command. You should convert all uses of delay_factor and max_loops
+over to read_timeout=x where x is the total number of seconds to wait
+before timing out.\n"""
+ warnings.warn(msg, DeprecationWarning)
+
+ if expect_string is not None:
+ search_pattern = expect_string
+ else:
+ search_pattern = self._prompt_handler(auto_find_prompt)
+
+ if normalize:
+ command_string = self.normalize_cmd(command_string)
+
+ # Start the clock
+ start_time = time.time()
+ self.write_channel(command_string)
+ new_data = ""
+
+ cmd = command_string.strip()
+ if cmd and cmd_verify:
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
+
+ MAX_CHARS = 2_000_000
+ DEQUE_SIZE = 20
+ output = ""
+ # Check only the past N-reads. This is for the case where the output is
+ # very large (i.e. searching a very large string for a pattern a whole bunch of times)
+ past_n_reads: Deque[str] = deque(maxlen=DEQUE_SIZE)
+ first_line_processed = False
- if normalize:
- command_string = self.normalize_cmd(command_string)
+ # Keep reading data until search_pattern is found or until read_timeout
+ while time.time() - start_time < read_timeout:
+ if new_data:
+ output += new_data
+ past_n_reads.append(new_data)
- time.sleep(delay_factor * loop_delay)
- self.clear_buffer()
- self.write_channel(command_string)
- new_data = ""
+ # Case where we haven't processed the first_line yet (there is a potential issue
+ # in the first line (in cases where the line is repainted).
+ if not first_line_processed:
+ output, first_line_processed = self._first_line_handler(
+ output, search_pattern
+ )
+ # Check if we have already found our pattern
+ if re.search(search_pattern, output):
+ break
- cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
- if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
- # Strip off everything before the command echo (to avoid false positives on the prompt)
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- new_data = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
+ else:
+ if len(output) <= MAX_CHARS:
+ if re.search(search_pattern, output):
+ break
+ else:
+ # Switch to deque mode if output is greater than MAX_CHARS
+ # Check if pattern is in the past n reads
+ if re.search(search_pattern, "".join(past_n_reads)):
+ break
- i = 1
- output = ""
- past_three_reads = deque(maxlen=3)
- first_line_processed = False
+ time.sleep(loop_delay)
+ new_data = self.read_channel()
- # Keep reading data until search_pattern is found or until max_loops is reached.
- while i <= max_loops:
- if new_data:
- output += new_data
- past_three_reads.append(new_data)
-
- # Case where we haven't processed the first_line yet (there is a potential issue
- # in the first line (in cases where the line is repainted).
- if not first_line_processed:
- output, first_line_processed = self._first_line_handler(
- output, search_pattern
- )
- # Check if we have already found our pattern
- if re.search(search_pattern, output):
- break
+ else: # nobreak
+ msg = f"""
+Pattern not detected: {repr(search_pattern)} in output.
- else:
- # Check if pattern is in the past three reads
- if re.search(search_pattern, "".join(past_three_reads)):
- break
+Things you might try to fix this:
+1. Explicitly set your pattern using the expect_string argument.
+2. Increase the read_timeout to a larger value.
- time.sleep(delay_factor * loop_delay)
- i += 1
- new_data = self.read_channel()
- else: # nobreak
- raise IOError(
- "Search pattern never detected in send_command: {}".format(
- search_pattern
- )
- )
+You can also look at the Netmiko session_log or debug log for more information.
- output = self._sanitize_output(
- output,
- strip_command=strip_command,
- command_string=command_string,
- strip_prompt=strip_prompt,
- )
+"""
+ raise ReadTimeout(msg)
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
+ output = self._sanitize_output(
output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
+ strip_command=strip_command,
+ command_string=command_string,
+ strip_prompt=strip_prompt,
)
- # 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()
+ return_val = structured_data_converter(
+ command=command_string,
+ raw_data=output,
+ platform=self.device_type,
+ use_textfsm=use_textfsm,
+ use_ttp=use_ttp,
+ use_genie=use_genie,
+ textfsm_template=textfsm_template,
+ ttp_template=ttp_template,
)
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
- return output
+ return return_val
def send_command_expect(self, *args, **kwargs)
-
Support previous name of send_command method.
-
:param args: Positional arguments to send to send_command()
-:type args: list
-
:param kwargs: Keyword arguments to send to send_command()
-:type kwargs: dict
+
Support previous name of send_command method.
Source code
-
def send_command_expect(self, *args, **kwargs):
- """Support previous name of send_command method.
-
- :param args: Positional arguments to send to send_command()
- :type args: list
-
- :param kwargs: Keyword arguments to send to send_command()
- :type kwargs: dict
- """
+
def send_command_expect(
+ self, *args: Any, **kwargs: Any
+) -> Union[str, List[Any], Dict[str, Any]]:
+ """Support previous name of send_command method."""
return self.send_command(*args, **kwargs)
Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
-
:param command_string: The command to be executed on the remote device.
-:type command_string: str
-
:param delay_factor: Multiplying factor used to adjust delays (default: 1).
-:type delay_factor: int or float
-
:param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
-based upon self.timeout.
-:type max_loops: int
-
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
-:type strip_prompt: bool
-
:param strip_command: Remove the echo of the command from the output (default: True).
-:type strip_command: bool
-
:param normalize: Ensure the proper enter is sent at end of command (default: True).
-:type normalize: bool
-
:param use_textfsm: Process command output through TextFSM template (default: False).
-:type use_textfsm: bool
+
:param command_string: The command to be executed on the remote device.
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
+
:param strip_command: Remove the echo of the command from the output (default: True).
+
:param normalize: Ensure the proper enter is sent at end of command (default: True).
+
:param use_textfsm: Process command output through TextFSM template (default: False).
: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
+path, relative path, or name of file in current directory. (default: None).
+
:param use_ttp: Process command output through TTP template (default: False).
: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
+path, relative path, or name of file in current directory. (default: None).
+
:param use_genie: Process command output through PyATS/Genie parser (default: False).
+
:param cmd_verify: Verify command echo before proceeding (default: False).
Source code
@select_cmd_verify
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,
-):
+ command_string: str,
+ last_read: float = 2.0,
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ max_loops: Optional[int] = None,
+ strip_prompt: bool = True,
+ strip_command: bool = True,
+ normalize: bool = True,
+ use_textfsm: bool = False,
+ textfsm_template: Optional[str] = None,
+ use_ttp: bool = False,
+ ttp_template: Optional[str] = None,
+ use_genie: bool = False,
+ cmd_verify: bool = False,
+) -> Union[str, List[Any], Dict[str, Any]]:
"""Execute command_string on the SSH channel using a delay-based mechanism. Generally
used for show commands.
:param command_string: The command to be executed on the remote device.
- :type command_string: str
- :param delay_factor: Multiplying factor used to adjust delays (default: 1).
- :type delay_factor: int or float
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor. Will default to be
- based upon self.timeout.
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Remove the trailing router prompt from the output (default: True).
- :type strip_prompt: bool
:param strip_command: Remove the echo of the command from the output (default: True).
- :type strip_command: bool
:param normalize: Ensure the proper enter is sent at end of command (default: True).
- :type normalize: bool
:param use_textfsm: Process command output through TextFSM template (default: False).
- :type use_textfsm: 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).
- :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).
- :type cmd_verify: bool
-
- :param cmd_echo: Deprecated (use cmd_verify instead)
- :type cmd_echo: bool
"""
-
- # For compatibility; remove cmd_echo in Netmiko 4.x.x
- if cmd_echo is not None:
- cmd_verify = cmd_echo
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
output = ""
- delay_factor = self.select_delay_factor(delay_factor)
-
+ new_data = ""
if normalize:
command_string = self.normalize_cmd(command_string)
self.write_channel(command_string)
cmd = command_string.strip()
- # if cmd is just an "enter" skip this section
if cmd and cmd_verify:
- # Make sure you read until you detect the command echo (avoid getting out of sync)
- new_data = self.read_until_pattern(pattern=re.escape(cmd))
- new_data = self.normalize_linefeeds(new_data)
-
- # Strip off everything before the command echo
- if new_data.count(cmd) == 1:
- new_data = new_data.split(cmd)[1:]
- new_data = self.RESPONSE_RETURN.join(new_data)
- new_data = new_data.lstrip()
- output = f"{cmd}{self.RESPONSE_RETURN}{new_data}"
- else:
- # cmd is in the actual output (not just echoed)
- output = new_data
-
- log.debug(f"send_command_timing current output: {output}")
-
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
+ new_data = self.command_echo_read(cmd=cmd, read_timeout=10)
+ output += new_data
+ output += self.read_channel_timing(
+ last_read=last_read, read_timeout=read_timeout
)
+
output = self._sanitize_output(
output,
strip_command=strip_command,
command_string=command_string,
strip_prompt=strip_prompt,
)
-
- # If both TextFSM, TTP and Genie are set, try TextFSM then TTP then Genie
- if use_textfsm:
- structured_output = get_structured_data(
- output,
- platform=self.device_type,
- command=command_string.strip(),
- template=textfsm_template,
- )
- # 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()
- )
- # If we have structured data; return it.
- if not isinstance(structured_output, str):
- return structured_output
-
- log.debug(f"send_command_timing final output: {output}")
- return output
def send_config_from_file(
+ self, config_file: Union[str, bytes, "PathLike[Any]"], **kwargs: Any
+) -> str:
"""
Send configuration commands down the SSH channel from a file.
@@ -4107,59 +4562,57 @@
Methods
**kwargs are passed to send_config_set method.
:param config_file: Path to configuration file to be sent to the device
- :type config_file: str
:param kwargs: params to be sent to send_config_set method
- :type kwargs: dict
"""
with io.open(config_file, "rt", encoding="utf-8") as cfg_file:
- return self.send_config_set(cfg_file, **kwargs)
Automatically exits/enters configuration mode.
:param config_commands: Multiple configuration commands to be sent to the device
- :type config_commands: list or string
:param exit_config_mode: Determines whether or not to exit config mode after complete
- :type exit_config_mode: bool
- :param delay_factor: Factor to adjust delays
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- :param max_loops: Controls wait time in conjunction with delay_factor (default: 150)
- :type max_loops: int
+ :param max_loops: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
:param strip_prompt: Determines whether or not to strip the prompt
- :type strip_prompt: bool
:param strip_command: Determines whether or not to strip the command
- :type strip_command: bool
+
+ :param read_timeout: Absolute timer to send to read_channel_timing. Should be rarely needed.
:param config_mode_command: The command to enter into config mode
- :type config_mode_command: str
:param cmd_verify: Whether or not to verify command echo for each command in config_set
- :type cmd_verify: bool
:param enter_config_mode: Do you enter config mode before sending config commands
- :type exit_config_mode: bool
:param error_pattern: Regular expression pattern to detect config errors in the
output.
- :type error_pattern: str
+
+ :param terminator: Regular expression pattern to use as an alternate terminator in certain
+ situations.
+
+ :param bypass_commands: Regular expression pattern indicating configuration commands
+ where cmd_verify is automatically disabled.
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if self.global_cmd_verify is not None:
+ cmd_verify = self.global_cmd_verify
+
+ if delay_factor is not None or max_loops is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
+ # Calculate an equivalent read_timeout (if using old settings)
+ # Eliminate in Netmiko 5.x
+ if read_timeout is None:
+ max_loops = 150 if max_loops is None else max_loops
+ delay_factor = 1.0 if delay_factor is None else delay_factor
+
+ # If delay_factor has been set, then look at global_delay_factor
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ read_timeout = calc_old_timeout(
+ max_loops=max_loops, delay_factor=delay_factor, loop_delay=0.1
+ )
+
+ if delay_factor is None:
+ delay_factor = self.select_delay_factor(0)
+ else:
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ if read_timeout is None:
+ read_timeout = 15
+ else:
+ read_timeout = read_timeout
+
if config_commands is None:
return ""
elif isinstance(config_commands, str):
@@ -4208,20 +4688,33 @@
Methods
if not hasattr(config_commands, "__iter__"):
raise ValueError("Invalid argument passed into send_config_set")
+ if bypass_commands is None:
+ # Commands where cmd_verify is automatically disabled reg-ex logical-or
+ bypass_commands = r"^banner .*$"
+
+ # Set bypass_commands="" to force no-bypass (usually for testing)
+ bypass_detected = False
+ if bypass_commands:
+ bypass_detected = any(
+ [True for cmd in config_commands if re.search(bypass_commands, cmd)]
+ )
+ if bypass_detected:
+ cmd_verify = False
+
# Send config commands
output = ""
if enter_config_mode:
- cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
- output += self.config_mode(*cfg_mode_args)
+ if config_mode_command:
+ output += self.config_mode(config_mode_command)
+ else:
+ output += self.config_mode()
- # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ # Perform output gathering line-by-line (legacy way)
if self.fast_cli and self._legacy_mode and not error_pattern:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
elif not cmd_verify:
for cmd in config_commands:
@@ -4230,35 +4723,25 @@
Methods
# Gather the output incrementally due to error_pattern requirements
if error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
if re.search(error_pattern, output, flags=re.M):
msg = f"Invalid input detected at command: {cmd}"
raise ConfigInvalidException(msg)
# Standard output gathering (no error_pattern)
if not error_pattern:
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+ output += self.read_channel_timing(read_timeout=read_timeout)
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
# Make sure command is echoed
- new_output = self.read_until_pattern(pattern=re.escape(cmd.strip()))
- output += new_output
-
- # We might capture next prompt in the original read
- pattern = f"(?:{re.escape(self.base_prompt)}|#)"
- if not re.search(pattern, new_output):
- # Make sure trailing prompt comes back (after command)
- # NX-OS has fast-buffering problem where it immediately echoes command
- # Even though the device hasn't caught up with processing command.
- new_output = self.read_until_pattern(pattern=pattern)
- output += new_output
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+
+ # Read until next prompt or terminator (#); the .*$ forces read of entire line
+ pattern = f"(?:{re.escape(self.base_prompt)}.*$|{terminator}.*$)"
+ output += self.read_until_pattern(pattern=pattern, re_flags=re.M)
if error_pattern:
if re.search(error_pattern, output, flags=re.M):
@@ -4272,8 +4755,89 @@
Any expect_string that is a null-string will use pattern based on
+device's prompt (unless expect_string argument is passed in via
+kwargs.
+
+Source code
+
def send_multiline(
+ self,
+ commands: Sequence[Union[str, List[str]]],
+ multiline: bool = True,
+ **kwargs: Any,
+) -> str:
+ """
+ commands should either be:
+
+ commands = [[cmd1, expect1], [cmd2, expect2], ...]]
+
+ Or
+
+ commands = [cmd1, cmd2, cmd3, ...]
+
+ Any expect_string that is a null-string will use pattern based on
+ device's prompt (unless expect_string argument is passed in via
+ kwargs.
+
+ """
+ output = ""
+ if multiline:
+ kwargs = self._multiline_kwargs(**kwargs)
+
+ default_expect_string = kwargs.pop("expect_string", None)
+ if not default_expect_string:
+ auto_find_prompt = kwargs.get("auto_find_prompt", True)
+ default_expect_string = self._prompt_handler(auto_find_prompt)
+
+ if commands and isinstance(commands[0], str):
+ # If list of commands just send directly using default_expect_string (probably prompt)
+ for cmd in commands:
+ cmd = str(cmd)
+ output += self._send_command_str(
+ cmd, expect_string=default_expect_string, **kwargs
+ )
+ else:
+ # If list of lists, then first element is cmd and second element is expect_string
+ for cmd_item in commands:
+ assert not isinstance(cmd_item, str)
+ cmd, expect_string = cmd_item
+ if not expect_string:
+ expect_string = default_expect_string
+ output += self._send_command_str(
+ cmd, expect_string=expect_string, **kwargs
+ )
+ return output
This method handles some differences that occur between various devices
early on in the session.
In general, it should include:
-self._test_channel_read()
+self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
-self.disable_paging()
self.set_terminal_width()
-self.clear_buffer()
+self.disable_paging()
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established
@@ -4321,24 +4884,19 @@
Methods
early on in the session.
In general, it should include:
- self._test_channel_read()
+ self._test_channel_read(pattern=r"some_pattern")
self.set_base_prompt()
- self.disable_paging()
self.set_terminal_width()
- self.clear_buffer()
+ self.disable_paging()
"""
self._test_channel_read()
self.set_base_prompt()
self.set_terminal_width()
- self.disable_paging()
-
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
-
:param command: Command string to send to the device
-:type command: str
-
:param delay_factor: See init: global_delay_factor
-:type delay_factor: int
+
:param command: Command string to send to the device
+
:param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
Source code
def set_terminal_width(
- self, command="", delay_factor=1, cmd_verify=False, pattern=None
-):
+ self,
+ command: str = "",
+ delay_factor: Optional[float] = None,
+ cmd_verify: bool = False,
+ pattern: Optional[str] = None,
+) -> str:
"""CLI terminals try to automatically adjust the line based on the width of the terminal.
This causes the output to get distorted when accessed programmatically.
Set terminal width to 511 which works on a broad set of devices.
:param command: Command string to send to the device
- :type command: str
- :param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
+ :param delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
"""
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
if not command:
return ""
- delay_factor = self.select_delay_factor(delay_factor)
command = self.normalize_cmd(command)
self.write_channel(command)
+
# Avoid cmd_verify here as terminal width must be set before doing cmd_verify
if cmd_verify and self.global_cmd_verify is not False:
output = self.read_until_pattern(pattern=re.escape(command.strip()))
@@ -4433,13 +5009,13 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Handler for devices like WLC, Extreme ERS that throw up characters prior to login."""
pass
@@ -4474,18 +5050,20 @@
Methods
ESC[2J
Code erase display
ESC[00;32m
-Color Green (30 to 37 are different colors) more general pattern is
-ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+Color Green (30 to 37 are different colors)
ESC[6n
Get cursor position
ESC[1D
-Move cursor position leftward by x characters (1 in this case)
+Move cursor position leftward by x characters (1 in this case)
+ESC[9999B
+Move cursor down N-lines (very large value is attempt to move to the
+very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
:param string_buffer: The string to be processed to remove ANSI escape codes
:type string_buffer: str
def strip_ansi_escape_codes(self, string_buffer: str) -> str:
"""
Remove any ANSI (VT100) ESC codes from the output
@@ -4506,10 +5084,11 @@
Methods
ESC[?6l Reset mode screen with options 640 x 200 monochrome (graphics)
ESC[?7l Disable line wrapping
ESC[2J Code erase display
- ESC[00;32m Color Green (30 to 37 are different colors) more general pattern is
- ESC[\d\d;\d\dm and ESC[\d\d;\d\d;\d\dm
+ ESC[00;32m Color Green (30 to 37 are different colors)
ESC[6n Get cursor position
ESC[1D Move cursor position leftward by x characters (1 in this case)
+ ESC[9999B Move cursor down N-lines (very large value is attempt to move to the
+ very bottom of the screen).
HP ProCurve and Cisco SG300 require this (possible others).
@@ -4531,7 +5110,8 @@
def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
:param a_string: Returned string from device
@@ -4642,6 +5233,7 @@
Methods
"""
response_list = a_string.split(self.RESPONSE_RETURN)
last_line = response_list[-1]
+
if self.base_prompt in last_line:
return self.RESPONSE_RETURN.join(response_list[:-1])
else:
@@ -4649,51 +5241,41 @@
Telnet login. Can be username/password or just password.
-
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
-:type pri_prompt_terminator: str
-
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
-:type alt_prompt_terminator: str
-
:param username_pattern: Pattern used to identify the username prompt
-:type username_pattern: str
-
:param delay_factor: See init: global_delay_factor
-:type delay_factor: int
-
:param max_loops: Controls the wait time in conjunction with the delay_factor
-(default: 20)
+
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
+
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
+
:param username_pattern: Pattern used to identify the username prompt
+
:param delay_factor: See init: global_delay_factor
+
:param max_loops: Controls the wait time in conjunction with the delay_factor
Source code
def telnet_login(
self,
- pri_prompt_terminator=r"#\s*$",
- alt_prompt_terminator=r">\s*$",
- username_pattern=r"(?:user:|username|login|user name)",
- pwd_pattern=r"assword",
- delay_factor=1,
- max_loops=20,
-):
+ pri_prompt_terminator: str = r"#\s*$",
+ alt_prompt_terminator: str = r">\s*$",
+ username_pattern: str = r"(?:user:|username|login|user name)",
+ pwd_pattern: str = r"assword",
+ delay_factor: float = 1.0,
+ max_loops: int = 20,
+) -> str:
"""Telnet login. Can be username/password or just password.
:param pri_prompt_terminator: Primary trailing delimiter for identifying a device prompt
- :type pri_prompt_terminator: str
:param alt_prompt_terminator: Alternate trailing delimiter for identifying a device prompt
- :type alt_prompt_terminator: str
:param username_pattern: Pattern used to identify the username prompt
- :type username_pattern: str
:param delay_factor: See __init__: global_delay_factor
- :type delay_factor: int
:param max_loops: Controls the wait time in conjunction with the delay_factor
- (default: 20)
"""
delay_factor = self.select_delay_factor(delay_factor)
- # FIX: Cleanup in future versions of Netmiko
+ # Revert telnet_login back to old speeds/delays
if delay_factor < 1:
if not self._legacy_mode and self.fast_cli:
delay_factor = 1
@@ -4719,6 +5301,7 @@
Methods
# Search for password pattern / send password
if re.search(pwd_pattern, output, flags=re.I):
# Sometimes username/password must be terminated with "\r" and not "\r\n"
+ assert isinstance(self.password, str)
self.write_channel(self.password + "\r")
time.sleep(0.5 * delay_factor)
output = self.read_channel()
@@ -4738,6 +5321,7 @@
Methods
time.sleep(0.5 * delay_factor)
i += 1
except EOFError:
+ assert self.remote_conn is not None
self.remote_conn.close()
msg = f"Login failed: {self.host}"
raise NetmikoAuthenticationException(msg)
@@ -4753,6 +5337,7 @@
Methods
return return_msg
msg = f"Login failed: {self.host}"
+ assert self.remote_conn is not None
self.remote_conn.close()
raise NetmikoAuthenticationException(msg)
@@ -4761,23 +5346,20 @@
Methods
def write_channel(self, out_data)
-
Generic handler that will write to both SSH and telnet channel.
+
Generic method that will write data out the channel.
:param out_data: data to be written to the channel
-:type out_data: str (can be either unicode/byte string)
+:type out_data: strSource code
-
def write_channel(self, out_data):
- """Generic handler that will write to both SSH and telnet channel.
+
@lock_channel
+@log_writes
+def write_channel(self, out_data: str) -> None:
+ """Generic method that will write data out the channel.
:param out_data: data to be written to the channel
- :type out_data: str (can be either unicode/byte string)
+ :type out_data: str
"""
- self._lock_netmiko_session()
- try:
- self._write_channel(out_data)
- finally:
- # Always unlock the SSH channel, even on exception.
- self._unlock_netmiko_session()
+ self.channel.write_channel(out_data)
@@ -4790,20 +5372,41 @@
Methods
Exception raised for invalid configuration error.
Source code
-
class ConfigInvalidException(Exception):
+
class ConfigInvalidException(NetmikoBaseException):
"""Exception raised for invalid configuration error."""
pass
self.socket_timeout = socket_timeout
@staticmethod
- def _read_file(file_name):
+ def _read_file(file_name: str) -> str:
with io.open(file_name, "rt", encoding="utf-8") as f:
return f.read()
@staticmethod
- def _tcl_newline_rationalize(tcl_string):
+ def _tcl_newline_rationalize(tcl_string: str) -> str:
r"""
When using put inside a TCL {} section the newline is considered a new TCL
statement and causes a missing curly-brace message. Convert "\n" to "\r". TCL
@@ -4881,17 +5491,22 @@
Try to determine the device type.
"""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Constructor of the SSHDetect class
"""
@@ -5341,10 +6031,10 @@
Methods
# Call the _test_channel_read() in base to clear initial data
output = BaseConnection._test_channel_read(self.connection)
self.initial_buffer = output
- self.potential_matches = {}
- self._results_cache = {}
+ self.potential_matches: Dict[str, int] = {}
+ self._results_cache: Dict[str, str] = {}
- def autodetect(self):
+ def autodetect(self) -> Union[str, None]:
"""
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
@@ -5356,6 +6046,7 @@
Methods
for device_type, autodetect_dict in SSH_MAPPER_BASE:
tmp_dict = autodetect_dict.copy()
call_method = tmp_dict.pop("dispatch")
+ assert isinstance(call_method, str)
autodetect_method = getattr(self, call_method)
accuracy = autodetect_method(**tmp_dict)
if accuracy:
@@ -5364,6 +6055,10 @@
Methods
best_match = sorted(
self.potential_matches.items(), key=lambda t: t[1], reverse=True
)
+ # WLC needs two different auto-dectect solutions
+ if "cisco_wlc_85" in best_match[0]:
+ best_match[0] = ("cisco_wlc", 99)
+
self.connection.disconnect()
return best_match[0][0]
@@ -5377,7 +6072,7 @@
Methods
self.connection.disconnect()
return best_match[0][0]
- def _send_command(self, cmd=""):
+ def _send_command(self, cmd: str = "") -> str:
"""
Handle reading/writing channel directly. It is also sanitizing the output received.
@@ -5393,11 +6088,11 @@
Methods
"""
self.connection.write_channel(cmd + "\n")
time.sleep(1)
- output = self.connection._read_channel_timing()
+ output = self.connection.read_channel_timing()
output = self.connection.strip_backspaces(output)
return output
- def _send_command_wrapper(self, cmd):
+ def _send_command_wrapper(self, cmd: str) -> str:
"""
Send command to the remote device with a caching feature to avoid sending the same command
twice based on the SSH_MAPPER_BASE dict cmd key.
@@ -5421,8 +6116,12 @@
Methods
return cached_results
def _autodetect_remote_version(
- self, search_patterns=None, re_flags=re.IGNORECASE, priority=99, **kwargs
- ):
+ self,
+ search_patterns: Optional[List[str]] = None,
+ re_flags: int = re.IGNORECASE,
+ priority: int = 99,
+ **kwargs: Any
+ ) -> int:
"""
Method to try auto-detect the device type, by matching a regular expression on the reported
remote version of the SSH server.
@@ -5443,7 +6142,10 @@
Methods
return 0
try:
- remote_version = self.connection.remote_conn.transport.remote_version
+ remote_conn = self.connection.remote_conn
+ assert isinstance(remote_conn, paramiko.Channel)
+ assert remote_conn.transport is not None
+ remote_version = remote_conn.transport.remote_version
for pattern in invalid_responses:
match = re.search(pattern, remote_version, flags=re.I)
if match:
@@ -5457,8 +6159,12 @@
Methods
return 0
def _autodetect_std(
- self, cmd="", search_patterns=None, re_flags=re.IGNORECASE, priority=99
- ):
+ self,
+ cmd: str = "",
+ search_patterns: Optional[List[str]] = None,
+ re_flags: int = re.IGNORECASE,
+ priority: int = 99,
+ ) -> int:
"""
Standard method to try to auto-detect the device type. This method will be called for each
device_type present in SSH_MAPPER_BASE dict ('dispatch' key). It will attempt to send a
@@ -5483,6 +6189,7 @@
Methods
r"%Error",
r"command not found",
r"Syntax Error: unexpected argument",
+ r"% Unrecognized command found at",
]
if not cmd or not search_patterns:
return 0
@@ -5516,7 +6223,7 @@
Returns
Source code
-
def autodetect(self):
+
def autodetect(self) -> Union[str, None]:
"""
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
@@ -5528,6 +6235,7 @@
Returns
for device_type, autodetect_dict in SSH_MAPPER_BASE:
tmp_dict = autodetect_dict.copy()
call_method = tmp_dict.pop("dispatch")
+ assert isinstance(call_method, str)
autodetect_method = getattr(self, call_method)
accuracy = autodetect_method(**tmp_dict)
if accuracy:
@@ -5536,6 +6244,10 @@
Returns
best_match = sorted(
self.potential_matches.items(), key=lambda t: t[1], reverse=True
)
+ # WLC needs two different auto-dectect solutions
+ if "cisco_wlc_85" in best_match[0]:
+ best_match[0] = ("cisco_wlc", 99)
+
self.connection.disconnect()
return best_match[0][0]
@@ -5577,11 +6289,13 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class IpInfusionOcNOSTelnet(IpInfusionOcNOSBase):
"""IP Infusion OcNOS Telnet driver."""
- def _process_option(self, tsocket, command, option):
+ def _process_option(self, tsocket: socket, command: bytes, option: bytes) -> None:
"""
For all telnet options, re-implement the default telnetlib behaviour
and refuse to handle any options. If the server expresses interest in
@@ -402,14 +348,16 @@
class IpInfusionOcNOSTelnet(IpInfusionOcNOSBase):
"""IP Infusion OcNOS Telnet driver."""
- def _process_option(self, tsocket, command, option):
+ def _process_option(self, tsocket: socket, command: bytes, option: bytes) -> None:
"""
For all telnet options, re-implement the default telnetlib behaviour
and refuse to handle any options. If the server expresses interest in
@@ -76,14 +81,16 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class IpInfusionOcNOSTelnet(IpInfusionOcNOSBase):
"""IP Infusion OcNOS Telnet driver."""
- def _process_option(self, tsocket, command, option):
+ def _process_option(self, tsocket: socket, command: bytes, option: bytes) -> None:
"""
For all telnet options, re-implement the default telnetlib behaviour
and refuse to handle any options. If the server expresses interest in
@@ -696,14 +626,16 @@
Implement methods for interacting with Juniper Networks devices.
-
Disables enable() and check_enable_mode()
-methods.
+
methods.
Overrides several methods for Juniper-specific compatibility.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implement methods for interacting with Juniper ScreenOS devices.
@@ -339,259 +316,143 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class JuniperScreenOsSSH(BaseConnection):
+
class JuniperScreenOsSSH(NoEnable, NoConfig, BaseConnection):
"""
Implement methods for interacting with Juniper ScreenOS devices.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
- Prepare the session after the connection has been established.
-
- Disable paging (the '--more--' prompts).
- Set the base prompt for interaction ('>').
+ ScreenOS can be configured to require: Accept this agreement y/[n]
"""
- self._test_channel_read()
+ terminator = r"\->"
+ pattern = rf"(Accept this|{terminator})"
+ data = self._test_channel_read(pattern=pattern)
+ if "Accept this" in data:
+ self.write_channel("y")
+ data += self._test_channel_read(pattern=terminator)
+
self.set_base_prompt()
self.disable_paging(command="set console page 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_enable_mode(self, *args, **kwargs):
- """No enable mode on Juniper ScreenOS."""
- return True
-
- def enable(self, *args, **kwargs):
- """No enable mode on Juniper ScreenOS."""
- return ""
-
- def exit_enable_mode(self, *args, **kwargs):
- """No enable mode on Juniper ScreenOS."""
- return ""
-
- def check_config_mode(self, *args, **kwargs):
- """No configuration mode on Juniper ScreenOS."""
- return False
- def config_mode(self, *args, **kwargs):
- """No configuration mode on Juniper ScreenOS."""
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No configuration mode on Juniper ScreenOS."""
- return ""
-
- def save_config(self, cmd="save config", confirm=False, confirm_response=""):
+ def save_config(
+ self,
+ cmd: str = "save config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Save Config."""
- return self.send_command(command_string=cmd)
Prepare the session after the connection has been established.
-
Disable paging (the '–more–' prompts).
-Set the base prompt for interaction ('>').
+
ScreenOS can be configured to require: Accept this agreement y/[n]
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
- Prepare the session after the connection has been established.
-
- Disable paging (the '--more--' prompts).
- Set the base prompt for interaction ('>').
+ ScreenOS can be configured to require: Accept this agreement y/[n]
"""
- self._test_channel_read()
+ terminator = r"\->"
+ pattern = rf"(Accept this|{terminator})"
+ data = self._test_channel_read(pattern=pattern)
+ if "Accept this" in data:
+ self.write_channel("y")
+ data += self._test_channel_read(pattern=terminator)
+
self.set_base_prompt()
- self.disable_paging(command="set console page 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
Implement methods for interacting with Juniper Networks devices.
-
Disables enable() and check_enable_mode()
-methods.
+
methods.
Overrides several methods for Juniper-specific compatibility.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class JuniperTelnet(JuniperBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
check:
command_string = commit check
- """
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- # Commit is very slow so this is needed.
- # FIX: Cleanup in future versions of Netmiko
- if delay_factor < 1:
- if not self._legacy_mode and self.fast_cli:
- delay_factor = 1
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
-
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -200,35 +183,27 @@
Module netmiko.juniper.juniper
output = self.config_mode()
# and_quit will get out of config mode on commit
- if and_quit:
- expect_string = re.escape(self.base_prompt)
- else:
- expect_string = None
+ expect_string = re.escape(self.base_prompt) if and_quit else None
- try:
- fast_cli_state = self.fast_cli
- self.fast_cli = False
- output += self.send_command(
- command_string,
- expect_string=expect_string,
- strip_prompt=False,
- strip_command=False,
- delay_factor=delay_factor,
- )
- finally:
- self.fast_cli = fast_cli_state
+ output += self._send_command_str(
+ command_string,
+ expect_string=expect_string,
+ strip_prompt=False,
+ strip_command=False,
+ read_timeout=read_timeout,
+ )
if commit_marker not in output:
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip the trailing router prompt from the output."""
a_string = super().strip_prompt(*args, **kwargs)
return self.strip_context_items(a_string)
- def strip_context_items(self, a_string):
+ def strip_context_items(self, a_string: str) -> str:
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
@@ -256,7 +231,7 @@
Module netmiko.juniper.juniper
return self.RESPONSE_RETURN.join(response_list[:-1])
return a_string
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -274,7 +249,7 @@
Implement methods for interacting with Juniper Networks devices.
-
Disables enable() and check_enable_mode()
-methods.
+
methods.
Overrides several methods for Juniper-specific compatibility.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class JuniperBase(BaseConnection):
+
class JuniperBase(NoEnable, BaseConnection):
"""
Implement methods for interacting with Juniper Networks devices.
- Disables `enable()` and `check_enable_mode()`
methods. Overrides several methods for Juniper-specific compatibility.
"""
- def __init__(self, *args, **kwargs):
- # Cisco-IOS 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):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.enter_cli_mode()
cmd = "set cli screen-width 511"
@@ -504,15 +448,15 @@
Classes
)
self.set_base_prompt()
- def _enter_shell(self):
+ def _enter_shell(self) -> str:
"""Enter the Bourne Shell."""
- return self.send_command("start shell sh", expect_string=r"[\$#]")
+ return self._send_command_str("start shell sh", expect_string=r"[\$#]")
- def _return_cli(self):
+ def _return_cli(self) -> str:
"""Return to the Juniper CLI."""
- return self.send_command("exit", expect_string=r"[#>]")
+ return self._send_command_str("exit", expect_string=r"[#>]")
- def enter_cli_mode(self):
+ def enter_cli_mode(self) -> None:
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
@@ -530,42 +474,32 @@
check:
command_string = commit check
- """
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- # Commit is very slow so this is needed.
- # FIX: Cleanup in future versions of Netmiko
- if delay_factor < 1:
- if not self._legacy_mode and self.fast_cli:
- delay_factor = 1
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
-
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -646,35 +577,27 @@
Classes
output = self.config_mode()
# and_quit will get out of config mode on commit
- if and_quit:
- expect_string = re.escape(self.base_prompt)
- else:
- expect_string = None
+ expect_string = re.escape(self.base_prompt) if and_quit else None
- try:
- fast_cli_state = self.fast_cli
- self.fast_cli = False
- output += self.send_command(
- command_string,
- expect_string=expect_string,
- strip_prompt=False,
- strip_command=False,
- delay_factor=delay_factor,
- )
- finally:
- self.fast_cli = fast_cli_state
+ output += self._send_command_str(
+ command_string,
+ expect_string=expect_string,
+ strip_prompt=False,
+ strip_command=False,
+ read_timeout=read_timeout,
+ )
if commit_marker not in output:
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip the trailing router prompt from the output."""
a_string = super().strip_prompt(*args, **kwargs)
return self.strip_context_items(a_string)
- def strip_context_items(self, a_string):
+ def strip_context_items(self, a_string: str) -> str:
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
@@ -702,7 +625,7 @@
Classes
return self.RESPONSE_RETURN.join(response_list[:-1])
return a_string
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -716,6 +639,7 @@
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string="]"):
+
def check_config_mode(self, check_string: str = "]", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
return super().check_config_mode(check_string=check_string)
check:
command_string = commit check
- """
- delay_factor = self.select_delay_factor(delay_factor)
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
- # Commit is very slow so this is needed.
- # FIX: Cleanup in future versions of Netmiko
- if delay_factor < 1:
- if not self._legacy_mode and self.fast_cli:
- delay_factor = 1
+ """
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if check and (confirm or confirm_delay or comment):
raise ValueError("Invalid arguments supplied with commit check")
-
if confirm_delay and not confirm:
raise ValueError(
"Invalid arguments supplied to commit method both confirm and check"
@@ -865,23 +775,15 @@
Methods
output = self.config_mode()
# and_quit will get out of config mode on commit
- if and_quit:
- expect_string = re.escape(self.base_prompt)
- else:
- expect_string = None
+ expect_string = re.escape(self.base_prompt) if and_quit else None
- try:
- fast_cli_state = self.fast_cli
- self.fast_cli = False
- output += self.send_command(
- command_string,
- expect_string=expect_string,
- strip_prompt=False,
- strip_command=False,
- delay_factor=delay_factor,
- )
- finally:
- self.fast_cli = fast_cli_state
+ output += self._send_command_str(
+ command_string,
+ expect_string=expect_string,
+ strip_prompt=False,
+ strip_command=False,
+ read_timeout=read_timeout,
+ )
if commit_marker not in output:
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
@@ -890,7 +792,7 @@
def enter_cli_mode(self) -> None:
"""Check if at shell prompt root@ and go into CLI."""
delay_factor = self.select_delay_factor(delay_factor=0)
count = 0
@@ -947,21 +837,23 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.enter_cli_mode()
cmd = "set cli screen-width 511"
@@ -1016,7 +896,7 @@
Methods
This method removes those lines.
Source code
-
def strip_context_items(self, a_string):
+
def strip_context_items(self, a_string: str) -> str:
"""Strip Juniper-specific output.
Juniper will also put a configuration context:
@@ -1052,7 +932,7 @@
Methods
Strip the trailing router prompt from the output.
Source code
-
def strip_prompt(self, *args, **kwargs):
+
def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip the trailing router prompt from the output."""
a_string = super().strip_prompt(*args, **kwargs)
return self.strip_context_items(a_string)
Implement methods for interacting with Juniper Networks devices.
-
Disables enable() and check_enable_mode()
-methods.
+
methods.
Overrides several methods for Juniper-specific compatibility.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implement methods for interacting with Juniper Networks devices.
-
Disables enable() and check_enable_mode()
-methods.
+
methods.
Overrides several methods for Juniper-specific compatibility.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class JuniperTelnet(JuniperBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
Implement methods for interacting with Juniper ScreenOS devices.
@@ -93,259 +75,143 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class JuniperScreenOsSSH(BaseConnection):
+
class JuniperScreenOsSSH(NoEnable, NoConfig, BaseConnection):
"""
Implement methods for interacting with Juniper ScreenOS devices.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
- Prepare the session after the connection has been established.
-
- Disable paging (the '--more--' prompts).
- Set the base prompt for interaction ('>').
+ ScreenOS can be configured to require: Accept this agreement y/[n]
"""
- self._test_channel_read()
+ terminator = r"\->"
+ pattern = rf"(Accept this|{terminator})"
+ data = self._test_channel_read(pattern=pattern)
+ if "Accept this" in data:
+ self.write_channel("y")
+ data += self._test_channel_read(pattern=terminator)
+
self.set_base_prompt()
self.disable_paging(command="set console page 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_enable_mode(self, *args, **kwargs):
- """No enable mode on Juniper ScreenOS."""
- return True
- def enable(self, *args, **kwargs):
- """No enable mode on Juniper ScreenOS."""
- return ""
-
- def exit_enable_mode(self, *args, **kwargs):
- """No enable mode on Juniper ScreenOS."""
- return ""
-
- def check_config_mode(self, *args, **kwargs):
- """No configuration mode on Juniper ScreenOS."""
- return False
-
- def config_mode(self, *args, **kwargs):
- """No configuration mode on Juniper ScreenOS."""
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No configuration mode on Juniper ScreenOS."""
- return ""
-
- def save_config(self, cmd="save config", confirm=False, confirm_response=""):
+ def save_config(
+ self,
+ cmd: str = "save config",
+ confirm: bool = False,
+ confirm_response: str = "",
+ ) -> str:
"""Save Config."""
- return self.send_command(command_string=cmd)
Prepare the session after the connection has been established.
-
Disable paging (the '–more–' prompts).
-Set the base prompt for interaction ('>').
+
ScreenOS can be configured to require: Accept this agreement y/[n]
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
- Prepare the session after the connection has been established.
-
- Disable paging (the '--more--' prompts).
- Set the base prompt for interaction ('>').
+ ScreenOS can be configured to require: Accept this agreement y/[n]
"""
- self._test_channel_read()
+ terminator = r"\->"
+ pattern = rf"(Accept this|{terminator})"
+ data = self._test_channel_read(pattern=pattern)
+ if "Accept this" in data:
+ self.write_channel("y")
+ data += self._test_channel_read(pattern=terminator)
+
self.set_base_prompt()
- self.disable_paging(command="set console page 0")
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class KeymileNOSSSH(CiscoIosBase):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.set_base_prompt()
self.disable_paging()
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def _test_channel_read(self, count=40, pattern=""):
+ def _test_channel_read(self, count: int = 40, pattern: str = "") -> str:
"""Since Keymile NOS always returns True on paramiko.connect() we
check the output for substring Login incorrect after connecting."""
output = super()._test_channel_read(count=count, pattern=pattern)
@@ -208,7 +181,7 @@
Classes
else:
return output
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Since Keymile NOS always returns True on paramiko.connect() we
check the output for substring Login incorrect after connecting."""
self._test_channel_read(pattern=r"(>|Login incorrect)")
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Since Keymile NOS always returns True on paramiko.connect() we
check the output for substring Login incorrect after connecting."""
self._test_channel_read(pattern=r"(>|Login incorrect)")
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
-
+
Class for platforms that have no enable mode.
+
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
Source code
-
class KeymileSSH(CiscoIosBase):
- def __init__(self, **kwargs):
+
class KeymileSSH(NoEnable, NoConfig, CiscoIosBase):
+ def __init__(self, **kwargs: Any) -> None:
kwargs.setdefault("default_enter", "\r\n")
- return super().__init__(**kwargs)
+ super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r">")
self.set_base_prompt()
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""Keymile does not use paging."""
return ""
- def check_config_mode(self, *args, **kwargs):
- """Keymile does not use config mode."""
- return False
-
- def config_mode(self, *args, **kwargs):
- """Keymile does not use config mode."""
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """Keymile does not use config mode."""
- return ""
-
- def check_enable_mode(self, *args, **kwargs):
- """Keymile does not use enable mode."""
- return False
-
- def enable(self, *args, **kwargs):
- """Keymile does not use enable mode."""
- return ""
-
- def exit_enable_mode(self, *args, **kwargs):
- """Keymile does not use enable mode."""
- return ""
-
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Remove appending empty line and prompt from output"""
- self._write_session_log(a_string)
a_string = a_string[:-1]
return super().strip_prompt(a_string=a_string)
- def set_base_prompt(self, pri_prompt_terminator=">", **kwargs):
- """ set prompt termination to >"""
- return super().set_base_prompt(pri_prompt_terminator=pri_prompt_terminator)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class KeymileNOSSSH(CiscoIosBase):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.set_base_prompt()
self.disable_paging()
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def _test_channel_read(self, count=40, pattern=""):
+ def _test_channel_read(self, count: int = 40, pattern: str = "") -> str:
"""Since Keymile NOS always returns True on paramiko.connect() we
check the output for substring Login incorrect after connecting."""
output = super()._test_channel_read(count=count, pattern=pattern)
@@ -227,7 +200,7 @@
Classes
else:
return output
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Since Keymile NOS always returns True on paramiko.connect() we
check the output for substring Login incorrect after connecting."""
self._test_channel_read(pattern=r"(>|Login incorrect)")
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""Since Keymile NOS always returns True on paramiko.connect() we
check the output for substring Login incorrect after connecting."""
self._test_channel_read(pattern=r"(>|Login incorrect)")
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
-
+
Class for platforms that have no enable mode.
+
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
Source code
-
class KeymileSSH(CiscoIosBase):
- def __init__(self, **kwargs):
+
class KeymileSSH(NoEnable, NoConfig, CiscoIosBase):
+ def __init__(self, **kwargs: Any) -> None:
kwargs.setdefault("default_enter", "\r\n")
- return super().__init__(**kwargs)
+ super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r">")
self.set_base_prompt()
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""Keymile does not use paging."""
return ""
- def check_config_mode(self, *args, **kwargs):
- """Keymile does not use config mode."""
- return False
-
- def config_mode(self, *args, **kwargs):
- """Keymile does not use config mode."""
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """Keymile does not use config mode."""
- return ""
-
- def check_enable_mode(self, *args, **kwargs):
- """Keymile does not use enable mode."""
- return False
-
- def enable(self, *args, **kwargs):
- """Keymile does not use enable mode."""
- return ""
-
- def exit_enable_mode(self, *args, **kwargs):
- """Keymile does not use enable mode."""
- return ""
-
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Remove appending empty line and prompt from output"""
- self._write_session_log(a_string)
a_string = a_string[:-1]
return super().strip_prompt(a_string=a_string)
- def set_base_prompt(self, pri_prompt_terminator=">", **kwargs):
- """ set prompt termination to >"""
- return super().set_base_prompt(pri_prompt_terminator=pri_prompt_terminator)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
def exit_enable_mode(self, exit_command: str = "exit") -> str:
"""Exit enable mode."""
delay_factor = self.select_delay_factor(delay_factor=0)
+ # You can run into a timing issue here if the time.sleep is too small
+ if delay_factor < 1:
+ delay_factor = 1
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
@@ -514,7 +528,7 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
return super().session_preparation()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
def exit_enable_mode(self, exit_command: str = "exit") -> str:
"""Exit enable mode."""
delay_factor = self.select_delay_factor(delay_factor=0)
+ # You can run into a timing issue here if the time.sleep is too small
+ if delay_factor < 1:
+ delay_factor = 1
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
@@ -680,7 +723,7 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
return super().session_preparation()
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
def exit_config_mode(self, exit_config: str = "exit", pattern: str = "#") -> str:
"""Mellanox does not support a single command to completely exit configuration mode.
Consequently, need to keep checking and sending "exit".
@@ -304,12 +312,15 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
def exit_config_mode(self, exit_config: str = "exit", pattern: str = "#") -> str:
"""Mellanox does not support a single command to completely exit configuration mode.
Consequently, need to keep checking and sending "exit".
@@ -356,12 +395,15 @@
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
-
+
Mikrotik RouterOS SSH driver.
Source code
class MikrotikRouterOsSSH(MikrotikBase):
@@ -190,6 +60,7 @@
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
-
+
Mikrotik SwitchOS SSH driver.
Source code
class MikrotikSwitchOsSSH(MikrotikBase):
@@ -389,6 +130,7 @@
from netmiko.cisco_base_connection import CiscoSSHConnection
+
from typing import Any, Union, List, Dict, Optional
+from netmiko.no_enable import NoEnable
+from netmiko.cisco_base_connection import CiscoSSHConnection
-class MikrotikBase(CiscoSSHConnection):
+class MikrotikBase(NoEnable, CiscoSSHConnection):
"""Common Methods for Mikrotik RouterOS and SwitchOS"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r\n"
@@ -36,15 +38,13 @@
Module netmiko.mikrotik.mikrotik_ssh
return super().__init__(**kwargs)
- def session_preparation(self, *args, **kwargs):
+ def session_preparation(self, *args: Any, **kwargs: Any) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- # Clear the read buffer
- self.write_channel(self.RETURN)
+ self._test_channel_read(pattern=r"\].*>")
self.set_base_prompt()
- self.clear_buffer()
- def _modify_connection_params(self):
+ def _modify_connection_params(self) -> None:
"""Append login options to username
c: disable console colors
e: enable dumb terminal mode
@@ -52,72 +52,83 @@
Module netmiko.mikrotik.mikrotik_ssh
w511: set term width
h4098: set term height
"""
- self.username += "+cetw511h4098"
+ self.username += "+ctw511h4098"
- def disable_paging(self, *args, **kwargs):
- """Microtik does not have paging by default."""
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
+ """Mikrotik does not have paging by default."""
return ""
- def check_enable_mode(self, *args, **kwargs):
- """No enable mode on RouterOS"""
- pass
-
- def enable(self, *args, **kwargs):
- """No enable mode on RouterOS."""
- pass
-
- def exit_enable_mode(self, *args, **kwargs):
- """No enable mode on RouterOS."""
- return ""
-
- def save_config(self, *args, **kwargs):
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
"""No save command, all configuration is atomic"""
- pass
+ return ""
- def config_mode(self):
- """No configuration mode on Microtik"""
+ def config_mode(
+ self, config_command: str = "", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ """No configuration mode on Mikrotik"""
self._in_config_mode = True
return ""
- def check_config_mode(self, check_string=""):
+ def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
"""Checks whether in configuration mode. Returns a boolean."""
return self._in_config_mode
- def exit_config_mode(self, exit_config=">"):
- """No configuration mode on Microtik"""
+ def exit_config_mode(self, exit_config: str = ">", pattern: str = "") -> str:
+ """No configuration mode on Mikrotik"""
self._in_config_mode = False
return ""
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
- MT adds some garbage trailing newlines, so
- trim the last two lines from the output.
- :param a_string: Returned string from device
- :type a_string: str
+ Mikrotik just does a lot of formatting/has ansi escape codes in output so
+ we need a special handler here.
+
+ There can be two trailing instances of the prompt probably due to
+ repainting.
"""
response_list = a_string.split(self.RESPONSE_RETURN)
- last_line = response_list[-2]
+ last_line = response_list[-1]
+
+ # Drop the first trailing prompt
if self.base_prompt in last_line:
- return self.RESPONSE_RETURN.join(response_list[:-2])
+ a_string = self.RESPONSE_RETURN.join(response_list[:-1])
+ a_string = a_string.rstrip()
+ # Now it should be just normal: call the parent method
+ a_string = super().strip_prompt(a_string)
+ return a_string.strip()
else:
+ # Unexpected just return the original string
return a_string
- def strip_command(self, command_string, output):
- """
- Strip command_string from output string
-
- MT returns, the Command\nRouterpromptCommand\n\n
- start the defaut return at len(self.get_prompt())+2*len(command)+1
-
- :param command_string: The command string sent to the device
- :type command_string: str
-
- :param output: The returned output as a result of the command string sen
- :type output: str
- """
- command_length = len(self.find_prompt()) + 2 * (len(command_string)) + 2
- return output[command_length:]
+ def set_base_prompt(
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = ">",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
+ """Strip the trailing space off."""
+ prompt = super().set_base_prompt(
+ pri_prompt_terminator=pri_prompt_terminator,
+ alt_prompt_terminator=alt_prompt_terminator,
+ delay_factor=delay_factor,
+ pattern=pattern,
+ )
+ prompt = prompt.strip()
+ self.base_prompt = prompt
+ return self.base_prompt
+
+ def send_command_timing( # type: ignore
+ self,
+ command_string: str,
+ cmd_verify: bool = True,
+ **kwargs: Any,
+ ) -> Union[str, List[Any], Dict[str, Any]]:
+ """Force cmd_verify to be True due to all of the line repainting"""
+ return super()._send_command_timing_str(
+ command_string=command_string, cmd_verify=cmd_verify, **kwargs
+ )
class MikrotikRouterOsSSH(MikrotikBase):
@@ -146,143 +157,13 @@
Classes
(**kwargs)
-
Common Methods for Mikrotik RouterOS and SwitchOS
-
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
-
+
Common Methods for Mikrotik RouterOS and SwitchOS
Source code
-
class MikrotikBase(CiscoSSHConnection):
+
class MikrotikBase(NoEnable, CiscoSSHConnection):
"""Common Methods for Mikrotik RouterOS and SwitchOS"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r\n"
@@ -290,15 +171,13 @@
Classes
return super().__init__(**kwargs)
- def session_preparation(self, *args, **kwargs):
+ def session_preparation(self, *args: Any, **kwargs: Any) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
- # Clear the read buffer
- self.write_channel(self.RETURN)
+ self._test_channel_read(pattern=r"\].*>")
self.set_base_prompt()
- self.clear_buffer()
- def _modify_connection_params(self):
+ def _modify_connection_params(self) -> None:
"""Append login options to username
c: disable console colors
e: enable dumb terminal mode
@@ -306,75 +185,87 @@
Classes
w511: set term width
h4098: set term height
"""
- self.username += "+cetw511h4098"
-
- def disable_paging(self, *args, **kwargs):
- """Microtik does not have paging by default."""
- return ""
-
- def check_enable_mode(self, *args, **kwargs):
- """No enable mode on RouterOS"""
- pass
-
- def enable(self, *args, **kwargs):
- """No enable mode on RouterOS."""
- pass
+ self.username += "+ctw511h4098"
- def exit_enable_mode(self, *args, **kwargs):
- """No enable mode on RouterOS."""
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
+ """Mikrotik does not have paging by default."""
return ""
- def save_config(self, *args, **kwargs):
+ def save_config(self, *args: Any, **kwargs: Any) -> str:
"""No save command, all configuration is atomic"""
- pass
+ return ""
- def config_mode(self):
- """No configuration mode on Microtik"""
+ def config_mode(
+ self, config_command: str = "", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ """No configuration mode on Mikrotik"""
self._in_config_mode = True
return ""
- def check_config_mode(self, check_string=""):
+ def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
"""Checks whether in configuration mode. Returns a boolean."""
return self._in_config_mode
- def exit_config_mode(self, exit_config=">"):
- """No configuration mode on Microtik"""
+ def exit_config_mode(self, exit_config: str = ">", pattern: str = "") -> str:
+ """No configuration mode on Mikrotik"""
self._in_config_mode = False
return ""
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
- MT adds some garbage trailing newlines, so
- trim the last two lines from the output.
- :param a_string: Returned string from device
- :type a_string: str
+ Mikrotik just does a lot of formatting/has ansi escape codes in output so
+ we need a special handler here.
+
+ There can be two trailing instances of the prompt probably due to
+ repainting.
"""
response_list = a_string.split(self.RESPONSE_RETURN)
- last_line = response_list[-2]
+ last_line = response_list[-1]
+
+ # Drop the first trailing prompt
if self.base_prompt in last_line:
- return self.RESPONSE_RETURN.join(response_list[:-2])
+ a_string = self.RESPONSE_RETURN.join(response_list[:-1])
+ a_string = a_string.rstrip()
+ # Now it should be just normal: call the parent method
+ a_string = super().strip_prompt(a_string)
+ return a_string.strip()
else:
+ # Unexpected just return the original string
return a_string
- def strip_command(self, command_string, output):
- """
- Strip command_string from output string
-
- MT returns, the Command\nRouterpromptCommand\n\n
- start the defaut return at len(self.get_prompt())+2*len(command)+1
-
- :param command_string: The command string sent to the device
- :type command_string: str
-
- :param output: The returned output as a result of the command string sen
- :type output: str
- """
- command_length = len(self.find_prompt()) + 2 * (len(command_string)) + 2
- return output[command_length:]
start the defaut return at len(self.get_prompt())+2*len(command)+1
-
- :param command_string: The command string sent to the device
- :type command_string: str
-
- :param output: The returned output as a result of the command string sen
- :type output: str
-
+
Strip the trailing space off.
Source code
-
def strip_command(self, command_string, output):
- """
- Strip command_string from output string
-
- MT returns, the Command\nRouterpromptCommand\n\n
- start the defaut return at len(self.get_prompt())+2*len(command)+1
-
- :param command_string: The command string sent to the device
- :type command_string: str
-
- :param output: The returned output as a result of the command string sen
- :type output: str
- """
- command_length = len(self.find_prompt()) + 2 * (len(command_string)) + 2
- return output[command_length:]
Strip the trailing router prompt from the output.
-MT adds some garbage trailing newlines, so
-trim the last two lines from the output.
-
:param a_string: Returned string from device
-:type a_string: str
+
Strip the trailing router prompt from the output.
+
Mikrotik just does a lot of formatting/has ansi escape codes in output so
+we need a special handler here.
+
There can be two trailing instances of the prompt probably due to
+repainting.
Source code
-
def strip_prompt(self, a_string):
+
def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output.
- MT adds some garbage trailing newlines, so
- trim the last two lines from the output.
- :param a_string: Returned string from device
- :type a_string: str
+ Mikrotik just does a lot of formatting/has ansi escape codes in output so
+ we need a special handler here.
+
+ There can be two trailing instances of the prompt probably due to
+ repainting.
"""
response_list = a_string.split(self.RESPONSE_RETURN)
- last_line = response_list[-2]
+ last_line = response_list[-1]
+
+ # Drop the first trailing prompt
if self.base_prompt in last_line:
- return self.RESPONSE_RETURN.join(response_list[:-2])
+ a_string = self.RESPONSE_RETURN.join(response_list[:-1])
+ a_string = a_string.rstrip()
+ # Now it should be just normal: call the parent method
+ a_string = super().strip_prompt(a_string)
+ return a_string.strip()
else:
+ # Unexpected just return the original string
return a_string
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
-
+
Mikrotik RouterOS SSH driver.
Source code
class MikrotikRouterOsSSH(MikrotikBase):
@@ -747,6 +492,7 @@
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
-
+
Mikrotik SwitchOS SSH driver.
Source code
class MikrotikSwitchOsSSH(MikrotikBase):
@@ -946,6 +562,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class MrvLxSSH(CiscoSSHConnection):
"""MRV Communications Driver (LX)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>|>>]")
self.set_base_prompt()
@@ -199,15 +172,26 @@
MRV has a >> for enable mode instead of # like Cisco
Source code
-
def check_enable_mode(self, check_string=">>"):
+
def check_enable_mode(self, check_string: str = ">>") -> bool:
"""MRV has a >> for enable mode instead of # like Cisco"""
return super().check_enable_mode(check_string=check_string)
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>|>>]")
self.set_base_prompt()
@@ -273,9 +262,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class MrvOptiswitchSSH(CiscoSSHConnection):
"""MRV Communications Driver (OptiSwitch)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -464,13 +426,19 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -560,9 +544,8 @@
"""MRV Communications Driver (LX)."""
import time
import re
+from typing import Optional
from netmiko.cisco_base_connection import CiscoSSHConnection
@@ -33,7 +34,7 @@
Module netmiko.mrv.mrv_lx
class MrvLxSSH(CiscoSSHConnection):
"""MRV Communications Driver (LX)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>|>>]")
self.set_base_prompt()
@@ -43,15 +44,26 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class MrvLxSSH(CiscoSSHConnection):
"""MRV Communications Driver (LX)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>|>>]")
self.set_base_prompt()
@@ -218,15 +203,26 @@
MRV has a >> for enable mode instead of # like Cisco
Source code
-
def check_enable_mode(self, check_string=">>"):
+
def check_enable_mode(self, check_string: str = ">>") -> bool:
"""MRV has a >> for enable mode instead of # like Cisco"""
return super().check_enable_mode(check_string=check_string)
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>|>>]")
self.set_base_prompt()
@@ -292,9 +293,8 @@
"""MRV Communications Driver (OptiSwitch)."""
import time
import re
+from typing import Optional
from netmiko.cisco_base_connection import CiscoSSHConnection
@@ -33,7 +34,7 @@
Module netmiko.mrv.mrv_ssh
class MrvOptiswitchSSH(CiscoSSHConnection):
"""MRV Communications Driver (OptiSwitch)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -44,13 +45,19 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class MrvOptiswitchSSH(CiscoSSHConnection):
"""MRV Communications Driver (OptiSwitch)."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -228,13 +213,19 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -324,9 +331,8 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class NetAppcDotSSH(BaseConnection):
- def session_preparation(self):
+
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class NetAppcDotSSH(BaseConnection):
- def session_preparation(self):
+
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class NetgearProSafeSSH(CiscoSSHConnection):
"""ProSafe OS support"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r"
return super().__init__(**kwargs)
- def session_preparation(self):
- """ProSafe OS requires enabe mode to disable paging."""
+ def session_preparation(self) -> None:
+ """ProSafe OS requires enable mode to disable paging."""
self._test_channel_read()
self.set_base_prompt()
self.enable()
@@ -200,18 +173,30 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class NetgearProSafeSSH(CiscoSSHConnection):
"""ProSafe OS support"""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
if kwargs.get("default_enter") is None:
kwargs["default_enter"] = "\r"
return super().__init__(**kwargs)
- def session_preparation(self):
- """ProSafe OS requires enabe mode to disable paging."""
+ def session_preparation(self) -> None:
+ """ProSafe OS requires enable mode to disable paging."""
self._test_channel_read()
self.set_base_prompt()
self.enable()
@@ -235,18 +222,30 @@
class NoConfig:
+ """
+ Class for platforms that have no config mode.
+
+ check_config_mode returns True as the expectation is that configuration commands
+ can be executed directly. So in your current state, you are in "config mode" i.e.
+ you can make configuration changes.
+
+ If you truly cannot make any configuration changes to device then you should probably
+ overwrite check_config_mode in the platform specific driver and return False.
+ """
+
+ def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
+ return True
+
+ def config_mode(
+ self, config_command: str = "", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return ""
+
+ def exit_config_mode(self, exit_config: str = "", pattern: str = "") -> str:
+ return ""
+
+
+
+
+
+
+
+
+
+
Classes
+
+
+class NoConfig
+(*args, **kwargs)
+
+
+
Class for platforms that have no config mode.
+
check_config_mode returns True as the expectation is that configuration commands
+can be executed directly. So in your current state, you are in "config mode" i.e.
+you can make configuration changes.
+
If you truly cannot make any configuration changes to device then you should probably
+overwrite check_config_mode in the platform specific driver and return False.
+
+Source code
+
class NoConfig:
+ """
+ Class for platforms that have no config mode.
+
+ check_config_mode returns True as the expectation is that configuration commands
+ can be executed directly. So in your current state, you are in "config mode" i.e.
+ you can make configuration changes.
+
+ If you truly cannot make any configuration changes to device then you should probably
+ overwrite check_config_mode in the platform specific driver and return False.
+ """
+
+ def check_config_mode(self, check_string: str = "", pattern: str = "") -> bool:
+ return True
+
+ def config_mode(
+ self, config_command: str = "", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return ""
+
+ def exit_config_mode(self, exit_config: str = "", pattern: str = "") -> str:
+ return ""
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/netmiko/no_enable.html b/docs/netmiko/no_enable.html
new file mode 100644
index 000000000..6e122505c
--- /dev/null
+++ b/docs/netmiko/no_enable.html
@@ -0,0 +1,221 @@
+
+
+
+
+
+
+netmiko.no_enable API documentation
+
+
+
+
+
+
+
+
+
+
+
+
+
Module netmiko.no_enable
+
+
+
+Source code
+
from typing import Optional
+import re
+
+
+class NoEnable:
+ """
+ Class for platforms that have no enable mode.
+
+ Netmiko translates the meaning of "enable" mode to be a proxy for "can
+ go into config mode". In other words, that you ultimately have privileges
+ to execute configuration changes.
+
+ The expectation on platforms that have no method for elevating privileges
+ is that the standard default privileges allow configuration changes.
+
+ Consequently check_enable_mode returns True by default for platforms that
+ don't explicitly support enable mode.
+ """
+
+ def check_enable_mode(self, check_string: str = "") -> bool:
+ return True
+
+ def enable(
+ self,
+ cmd: str = "",
+ pattern: str = "",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
+ return ""
+
+ def exit_enable_mode(self, exit_command: str = "") -> str:
+ return ""
+
+
+
+
+
+
+
+
+
+
Classes
+
+
+class NoEnable
+(*args, **kwargs)
+
+
+
Class for platforms that have no enable mode.
+
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
+
+Source code
+
class NoEnable:
+ """
+ Class for platforms that have no enable mode.
+
+ Netmiko translates the meaning of "enable" mode to be a proxy for "can
+ go into config mode". In other words, that you ultimately have privileges
+ to execute configuration changes.
+
+ The expectation on platforms that have no method for elevating privileges
+ is that the standard default privileges allow configuration changes.
+
+ Consequently check_enable_mode returns True by default for platforms that
+ don't explicitly support enable mode.
+ """
+
+ def check_enable_mode(self, check_string: str = "") -> bool:
+ return True
+
+ def enable(
+ self,
+ cmd: str = "",
+ pattern: str = "",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
+ return ""
+
+ def exit_enable_mode(self, exit_command: str = "") -> str:
+ return ""
+ return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
@@ -194,7 +225,7 @@
Methods
Verify the file has been transferred correctly based on filesize.
Source code
-
def verify_file(self):
+
def verify_file(self) -> bool:
"""Verify the file has been transferred correctly based on filesize."""
if self.direction == "put":
return os.stat(self.source_file).st_size == self.remote_file_size(
@@ -204,7 +235,9 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
# 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_cmd))
+ output += self.read_until_prompt(read_entire_line=True)
else:
- output += self.read_until_prompt()
+ output += self.read_until_prompt(read_entire_line=True)
return output
- def _discard(self):
+ def _discard(self) -> str:
"""Discard changes from private candidate for Nokia SR OS"""
output = ""
if "@" in self.base_prompt:
@@ -215,11 +242,11 @@
Module netmiko.nokia.nokia_sros
if self.global_cmd_verify is not False:
new_output += self.read_until_pattern(pattern=re.escape(cmd))
if "@" not in new_output:
- new_output += self.read_until_prompt()
+ new_output += self.read_until_prompt(read_entire_line=True)
output += new_output
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip prompt from the output."""
output = super().strip_prompt(*args, **kwargs)
if "@" in self.base_prompt:
@@ -229,7 +256,7 @@
Module netmiko.nokia.nokia_sros
else:
return output
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -256,13 +283,30 @@
Implement methods for interacting with Nokia SR OS devices
@@ -387,131 +443,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
# 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_cmd))
+ output += self.read_until_prompt(read_entire_line=True)
else:
- output += self.read_until_prompt()
+ output += self.read_until_prompt(read_entire_line=True)
return output
- def _discard(self):
+ def _discard(self) -> str:
"""Discard changes from private candidate for Nokia SR OS"""
output = ""
if "@" in self.base_prompt:
@@ -691,11 +746,11 @@
Classes
if self.global_cmd_verify is not False:
new_output += self.read_until_pattern(pattern=re.escape(cmd))
if "@" not in new_output:
- new_output += self.read_until_prompt()
+ new_output += self.read_until_prompt(read_entire_line=True)
output += new_output
return output
- def strip_prompt(self, *args, **kwargs):
+ def strip_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Strip prompt from the output."""
output = super().strip_prompt(*args, **kwargs)
if "@" in self.base_prompt:
@@ -705,7 +760,7 @@
Classes
else:
return output
- def cleanup(self, command="logout"):
+ def cleanup(self, command: str = "logout") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -735,7 +790,9 @@
def check_enable_mode(self, check_string: str = "in admin mode") -> bool:
"""Check if in enable mode."""
cmd = "enable"
if "@" not in self.base_prompt:
cmd = "enable-admin"
self.write_channel(self.normalize_cmd(cmd))
- output = self.read_until_prompt_or_pattern(pattern="ssword")
+ output = self.read_until_prompt_or_pattern(
+ pattern="ssword", read_entire_line=True
+ )
if "ssword" in output:
self.write_channel(self.RETURN) # send ENTER to pass the password prompt
- self.read_until_prompt()
+ self.read_until_prompt(read_entire_line=True)
return check_string in output
@@ -772,7 +831,7 @@
Methods
Gracefully exit the SSH session.
Source code
-
def cleanup(self, command="logout"):
+
def cleanup(self, command: str = "logout") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -792,7 +851,7 @@
Methods
Activate changes from private candidate for Nokia SR OS
Source code
-
def commit(self, *args, **kwargs):
+
def commit(self, *args: Any, **kwargs: Any) -> str:
"""Activate changes from private candidate for Nokia SR OS"""
output = self._exit_all()
if "@" in self.base_prompt and "*(ex)[" in output:
@@ -809,31 +868,45 @@
def send_config_set(
+ self,
+ config_commands: Union[str, Sequence[str], TextIO, None] = None,
+ exit_config_mode: bool = None,
+ **kwargs: Any,
+) -> str:
"""Model driven CLI requires you not exit from configuration mode."""
if exit_config_mode is None:
# Set to False if model-driven CLI
@@ -915,14 +994,15 @@
Methods
Remove the > when navigating into the different config level.
Source code
-
def set_base_prompt(self, *args, **kwargs):
+
def set_base_prompt(self, *args: Any, **kwargs: Any) -> str:
"""Remove the > when navigating into the different config level."""
cur_base_prompt = super().set_base_prompt(*args, **kwargs)
match = re.search(r"\*?(.*?)(>.*)*#", cur_base_prompt)
if match:
# strip off >... from base_prompt; strip off leading *
- self.base_prompt = match.group(1)
- return self.base_prompt
+ return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
@@ -1128,7 +1239,7 @@
Methods
Verify the file has been transferred correctly based on filesize.
Source code
-
def verify_file(self):
+
def verify_file(self) -> bool:
"""Verify the file has been transferred correctly based on filesize."""
if self.direction == "put":
return os.stat(self.source_file).st_size == self.remote_file_size(
@@ -1138,7 +1249,9 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implement methods for interacting with PaloAlto devices.
@@ -56,140 +56,132 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class PaloAltoPanosSSH(PaloAltoPanosBase):
- pass
+ def _build_ssh_client(self) -> SSHClient:
+ """Prepare for Paramiko SSH connection."""
+ # Create instance of SSHClient object
+ # If not using SSH keys, we use noauth
+
+ if not self.use_keys:
+ remote_conn_pre: SSHClient = SSHClient_interactive()
+ else:
+ remote_conn_pre = SSHClient()
+
+ # Load host_keys for better SSH security
+ if self.system_host_keys:
+ remote_conn_pre.load_system_host_keys()
+ if self.alt_host_keys and path.isfile(self.alt_key_file):
+ remote_conn_pre.load_host_keys(self.alt_key_file)
+
+ # Default is to automatically add untrusted hosts (make sure appropriate for your env)
+ remote_conn_pre.set_missing_host_key_policy(self.key_policy)
+ return remote_conn_pre
Implement methods for interacting with PaloAlto devices.
@@ -255,131 +247,104 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
from typing import Optional, List, Any, Tuple
import re
-from netmiko.base_connection import BaseConnection
+import warnings
+from os import path
+from paramiko import SSHClient, Transport
+from netmiko.no_enable import NoEnable
+from netmiko.base_connection import BaseConnection, DELAY_FACTOR_DEPR_SIMPLE_MSG
-class PaloAltoPanosBase(BaseConnection):
+
+class SSHClient_interactive(SSHClient):
+ """Set noauth when manually handling SSH authentication."""
+
+ def pa_banner_handler(
+ self, title: str, instructions: str, prompt_list: List[Tuple[str, bool]]
+ ) -> List[str]:
+
+ resp = []
+ for prompt, echo in prompt_list:
+ if "Do you accept" in prompt:
+ resp.append("yes")
+ elif "ssword" in prompt:
+ assert isinstance(self.password, str)
+ resp.append(self.password)
+ return resp
+
+ def _auth(self, username: str, password: str, *args: Any) -> None:
+ """
+ _auth: args as of aug-2021
+ self,
+ username,
+ password,
+ pkey,
+ key_filenames,
+ allow_agent,
+ look_for_keys,
+ gss_auth,
+ gss_kex,
+ gss_deleg_creds,
+ gss_host,
+ passphrase,
+ """
+
+ # Just gets the password up to the pa_banner_handler
+ self.password = password
+ transport = self.get_transport()
+ assert isinstance(transport, Transport)
+ transport.auth_interactive(username, handler=self.pa_banner_handler)
+ return
+
+
+class PaloAltoPanosBase(NoEnable, BaseConnection):
"""
Implement methods for interacting with PaloAlto devices.
@@ -35,7 +81,7 @@
Module netmiko.paloalto.paloalto_panos
methods. Overrides several methods for PaloAlto-specific compatibility.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
@@ -43,49 +89,55 @@
(device_and_network or policy_and_objects or vsys or
no_vsys) and not partial:
Exception
+
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if (
device_and_network or policy_and_objects or vsys or no_vsys
@@ -132,24 +189,25 @@
Module netmiko.paloalto.paloalto_panos
# Enter config mode (if necessary)
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
expect_string="100%",
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
+ output += self.exit_config_mode()
if commit_marker not in output.lower():
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
return output
- def strip_command(self, command_string, output):
+ def strip_command(self, command_string: str, output: str) -> str:
"""Strip command_string from output string."""
output_list = output.split(command_string)
return self.RESPONSE_RETURN.join(output_list)
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output."""
response_list = a_string.split(self.RESPONSE_RETURN)
new_response_list = []
@@ -160,7 +218,7 @@
Module netmiko.paloalto.paloalto_panos
output = self.RESPONSE_RETURN.join(new_response_list)
return self.strip_context_items(output)
- def strip_context_items(self, a_string):
+ def strip_context_items(self, a_string: str) -> str:
"""Strip PaloAlto-specific output.
PaloAlto will also put a configuration context:
@@ -179,16 +237,7 @@
Module netmiko.paloalto.paloalto_panos
return a_string
- def send_command_expect(self, *args, **kwargs):
- """Palo Alto requires an extra delay"""
- return self.send_command(*args, **kwargs)
-
- def send_command(self, *args, **kwargs):
- """Palo Alto requires an extra delay"""
- kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5)
- return super().send_command(*args, **kwargs)
-
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -202,7 +251,25 @@
Module netmiko.paloalto.paloalto_panos
class PaloAltoPanosSSH(PaloAltoPanosBase):
- pass
+ def _build_ssh_client(self) -> SSHClient:
+ """Prepare for Paramiko SSH connection."""
+ # Create instance of SSHClient object
+ # If not using SSH keys, we use noauth
+
+ if not self.use_keys:
+ remote_conn_pre: SSHClient = SSHClient_interactive()
+ else:
+ remote_conn_pre = SSHClient()
+
+ # Load host_keys for better SSH security
+ if self.system_host_keys:
+ remote_conn_pre.load_system_host_keys()
+ if self.alt_host_keys and path.isfile(self.alt_key_file):
+ remote_conn_pre.load_host_keys(self.alt_key_file)
+
+ # Default is to automatically add untrusted hosts (make sure appropriate for your env)
+ remote_conn_pre.set_missing_host_key_policy(self.key_policy)
+ return remote_conn_pre
class PaloAltoPanosTelnet(PaloAltoPanosBase):
@@ -220,7 +287,7 @@
Implement methods for interacting with PaloAlto devices.
@@ -231,135 +298,108 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class PaloAltoPanosBase(BaseConnection):
+
class PaloAltoPanosBase(NoEnable, BaseConnection):
"""
Implement methods for interacting with PaloAlto devices.
@@ -367,7 +407,7 @@
Classes
methods. Overrides several methods for PaloAlto-specific compatibility.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
@@ -375,49 +415,55 @@
(device_and_network or policy_and_objects or vsys or
no_vsys) and not partial:
Exception
+
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if (
device_and_network or policy_and_objects or vsys or no_vsys
@@ -464,24 +515,25 @@
Classes
# Enter config mode (if necessary)
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
expect_string="100%",
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
+ output += self.exit_config_mode()
if commit_marker not in output.lower():
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
return output
- def strip_command(self, command_string, output):
+ def strip_command(self, command_string: str, output: str) -> str:
"""Strip command_string from output string."""
output_list = output.split(command_string)
return self.RESPONSE_RETURN.join(output_list)
- def strip_prompt(self, a_string):
+ def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output."""
response_list = a_string.split(self.RESPONSE_RETURN)
new_response_list = []
@@ -492,7 +544,7 @@
Classes
output = self.RESPONSE_RETURN.join(new_response_list)
return self.strip_context_items(output)
- def strip_context_items(self, a_string):
+ def strip_context_items(self, a_string: str) -> str:
"""Strip PaloAlto-specific output.
PaloAlto will also put a configuration context:
@@ -511,16 +563,7 @@
Classes
return a_string
- def send_command_expect(self, *args, **kwargs):
- """Palo Alto requires an extra delay"""
- return self.send_command(*args, **kwargs)
-
- def send_command(self, *args, **kwargs):
- """Palo Alto requires an extra delay"""
- kwargs["delay_factor"] = kwargs.get("delay_factor", 2.5)
- return super().send_command(*args, **kwargs)
-
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -534,6 +577,7 @@
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string="]"):
+
def check_config_mode(self, check_string: str = "]", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
- return super().check_config_mode(check_string=check_string)
(device_and_network or policy_and_objects or vsys or
no_vsys) and not partial:
Exception
+
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
if (
device_and_network or policy_and_objects or vsys or no_vsys
@@ -659,13 +698,14 @@
Methods
# Enter config mode (if necessary)
output = self.config_mode()
- output += self.send_command_expect(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
expect_string="100%",
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
)
+ output += self.exit_config_mode()
if commit_marker not in output.lower():
raise ValueError(f"Commit failed with the following errors:\n\n{output}")
@@ -673,27 +713,19 @@
+ self.set_base_prompt()
+
+ # PA devices can be really slow--try to make sure we are caught up
+ self.write_channel("show admins\n")
+ self._test_channel_read(pattern=r"Client")
+ self._test_channel_read(pattern=r"[>#]")
def strip_context_items(self, a_string: str) -> str:
"""Strip PaloAlto-specific output.
PaloAlto will also put a configuration context:
@@ -821,7 +837,7 @@
Methods
Strip the trailing router prompt from the output.
Source code
-
def strip_prompt(self, a_string):
+
def strip_prompt(self, a_string: str) -> str:
"""Strip the trailing router prompt from the output."""
response_list = a_string.split(self.RESPONSE_RETURN)
new_response_list = []
@@ -838,27 +854,31 @@
Implement methods for interacting with PaloAlto devices.
@@ -883,140 +903,132 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class PaloAltoPanosSSH(PaloAltoPanosBase):
- pass
+ def _build_ssh_client(self) -> SSHClient:
+ """Prepare for Paramiko SSH connection."""
+ # Create instance of SSHClient object
+ # If not using SSH keys, we use noauth
+
+ if not self.use_keys:
+ remote_conn_pre: SSHClient = SSHClient_interactive()
+ else:
+ remote_conn_pre = SSHClient()
+
+ # Load host_keys for better SSH security
+ if self.system_host_keys:
+ remote_conn_pre.load_system_host_keys()
+ if self.alt_host_keys and path.isfile(self.alt_key_file):
+ remote_conn_pre.load_host_keys(self.alt_key_file)
+
+ # Default is to automatically add untrusted hosts (make sure appropriate for your env)
+ remote_conn_pre.set_missing_host_key_policy(self.key_policy)
+ return remote_conn_pre
Implement methods for interacting with PaloAlto devices.
@@ -1082,131 +1094,104 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
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
-
+
Common methods for Pluribus.
Source code
-
class PluribusSSH(BaseConnection):
+
class PluribusSSH(NoConfig, BaseConnection):
"""Common methods for Pluribus."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._config_mode = False
- def disable_paging(self, command="pager off", delay_factor=1):
- """Make sure paging is disabled."""
- return super().disable_paging(command=command, delay_factor=delay_factor)
-
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the netmiko session."""
self._test_channel_read()
self.set_base_prompt()
self.disable_paging()
# Clear the read buffer
time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_config_mode(self, *args, **kwargs):
- """
- Pluribus devices don't have a config mode.
- Therefore it can be considered as always in config mode.
- """
- return self._config_mode
-
- def config_mode(self, *args, **kwargs):
- """No special actions to enter in config mode."""
- self._config_mode = True
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No special actions to exit config mode."""
- self._config_mode = False
- return ""
Pluribus devices don't have a config mode.
-Therefore it can be considered as always in config mode.
-
-Source code
-
def check_config_mode(self, *args, **kwargs):
- """
- Pluribus devices don't have a config mode.
- Therefore it can be considered as always in config mode.
- """
- return self._config_mode
-
-
-
-def config_mode(self, *args, **kwargs)
-
-
-
No special actions to enter in config mode.
-
-Source code
-
def config_mode(self, *args, **kwargs):
- """No special actions to enter in config mode."""
- self._config_mode = True
- return ""
import time
+from typing import Any
+
+from netmiko.no_config import NoConfig
from netmiko.base_connection import BaseConnection
-class PluribusSSH(BaseConnection):
+class PluribusSSH(NoConfig, BaseConnection):
"""Common methods for Pluribus."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._config_mode = False
- def disable_paging(self, command="pager off", delay_factor=1):
- """Make sure paging is disabled."""
- return super().disable_paging(command=command, delay_factor=delay_factor)
-
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the netmiko session."""
self._test_channel_read()
self.set_base_prompt()
self.disable_paging()
# Clear the read buffer
time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_config_mode(self, *args, **kwargs):
- """
- Pluribus devices don't have a config mode.
- Therefore it can be considered as always in config mode.
- """
- return self._config_mode
-
- def config_mode(self, *args, **kwargs):
- """No special actions to enter in config mode."""
- self._config_mode = True
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No special actions to exit config mode."""
- self._config_mode = False
- return ""
+ self.clear_buffer()
@@ -78,236 +60,32 @@
Classes
(*args, **kwargs)
-
Common methods for Pluribus.
-
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
-
+
Common methods for Pluribus.
Source code
-
class PluribusSSH(BaseConnection):
+
class PluribusSSH(NoConfig, BaseConnection):
"""Common methods for Pluribus."""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self._config_mode = False
- def disable_paging(self, command="pager off", delay_factor=1):
- """Make sure paging is disabled."""
- return super().disable_paging(command=command, delay_factor=delay_factor)
-
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the netmiko session."""
self._test_channel_read()
self.set_base_prompt()
self.disable_paging()
# Clear the read buffer
time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def check_config_mode(self, *args, **kwargs):
- """
- Pluribus devices don't have a config mode.
- Therefore it can be considered as always in config mode.
- """
- return self._config_mode
-
- def config_mode(self, *args, **kwargs):
- """No special actions to enter in config mode."""
- self._config_mode = True
- return ""
-
- def exit_config_mode(self, *args, **kwargs):
- """No special actions to exit config mode."""
- self._config_mode = False
- return ""
Pluribus devices don't have a config mode.
-Therefore it can be considered as always in config mode.
-
-Source code
-
def check_config_mode(self, *args, **kwargs):
- """
- Pluribus devices don't have a config mode.
- Therefore it can be considered as always in config mode.
- """
- return self._config_mode
-
-
-
-def config_mode(self, *args, **kwargs)
-
-
-
No special actions to enter in config mode.
-
-Source code
-
def config_mode(self, *args, **kwargs):
- """No special actions to enter in config mode."""
- self._config_mode = True
- return ""
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RadETXSSH(RadETXBase):
"""RAD ETX SSH Support."""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# Found that a global_delay_factor of 2 is needed at minimum for SSH to the Rad ETX.
kwargs.setdefault("global_delay_factor", 2)
return super().__init__(**kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
class RadETXSSH(RadETXBase):
"""RAD ETX SSH Support."""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# Found that a global_delay_factor of 2 is needed at minimum for SSH to the Rad ETX.
kwargs.setdefault("global_delay_factor", 2)
return super().__init__(**kwargs)
@@ -93,8 +97,14 @@
RAD ETX Support, Tested on RAD 203AX, 205A and 220A.
@@ -129,138 +142,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class RadETXBase(BaseConnection):
+
class RadETXBase(NoEnable, BaseConnection):
"""RAD ETX Support, Tested on RAD 203AX, 205A and 220A."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
self._test_channel_read()
self.set_base_prompt()
self.disable_paging(command="config term length 0")
@@ -268,37 +254,36 @@
Classes
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def save_config(self, cmd="admin save", confirm=False, confirm_response=""):
+ def save_config(
+ self, cmd: str = "admin save", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Saves Config Using admin save."""
if confirm:
- output = self.send_command_timing(command_string=cmd)
+ output = self._send_command_timing_str(command_string=cmd)
if confirm_response:
- output += self.send_command_timing(confirm_response)
+ output += self._send_command_timing_str(confirm_response)
else:
# Send enter by default
- output += self.send_command_timing(self.RETURN)
+ output += self._send_command_timing_str(self.RETURN)
else:
# Some devices are slow so match on trailing-prompt if you can
- output = self.send_command(command_string=cmd)
+ output = self._send_command_str(command_string=cmd)
return output
- def check_enable_mode(self, *args, **kwargs):
- """The Rad ETX software does not have an enable."""
- pass
-
- def enable(self, *args, **kwargs):
- """The Rad ETX software does not have an enable."""
- pass
-
- def exit_enable_mode(self, *args, **kwargs):
- """The Rad ETX software does not have an enable."""
- pass
-
- def config_mode(self, config_command="config", pattern=">config"):
+ def config_mode(
+ self,
+ config_command: str = "config",
+ pattern: str = ">config",
+ re_flags: int = 0,
+ ) -> str:
"""Enter into configuration mode on remote device."""
- 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 check_config_mode(self, check_string=">config", pattern=""):
+ def check_config_mode(
+ self, check_string: str = ">config", pattern: str = ""
+ ) -> bool:
"""
Checks if the device is in configuration mode or not.
@@ -306,12 +291,15 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RadETXSSH(RadETXBase):
"""RAD ETX SSH Support."""
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# Found that a global_delay_factor of 2 is needed at minimum for SSH to the Rad ETX.
kwargs.setdefault("global_delay_factor", 2)
return super().__init__(**kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RaisecomRoapSSH(RaisecomRoapBase):
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Raisecom presents with the following on login (in certain OS versions)
Login: user
@@ -199,6 +172,7 @@
Classes
if "Login:" in output:
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert self.password is not None
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -216,7 +190,7 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Raisecom presents with the following on login (in certain OS versions)
Login: user
@@ -240,6 +214,7 @@
Methods
if "Login:" in output:
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert self.password is not None
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -258,9 +233,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
class RaisecomRoapSSH(RaisecomRoapBase):
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Raisecom presents with the following on login (in certain OS versions)
Login: user
@@ -74,6 +79,7 @@
Module netmiko.raisecom.raisecom_roap
if "Login:" in output:
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert self.password is not None
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -85,7 +91,7 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RaisecomRoapBase(CiscoBaseConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -331,15 +312,18 @@
def check_config_mode(self, check_string: str = ")#", pattern: str = "#") -> bool:
"""
Checks if the device is in configuration mode or not.
"""
@@ -380,7 +364,7 @@
Methods
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -399,9 +383,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RaisecomRoapSSH(RaisecomRoapBase):
- def special_login_handler(self, delay_factor=1):
+ def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Raisecom presents with the following on login (in certain OS versions)
Login: user
@@ -594,6 +551,7 @@
Inherited members
if "Login:" in output:
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert self.password is not None
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -611,7 +569,7 @@
def special_login_handler(self, delay_factor: float = 1.0) -> None:
"""
Raisecom presents with the following on login (in certain OS versions)
Login: user
@@ -635,6 +593,7 @@
Methods
if "Login:" in output:
self.write_channel(self.username + self.RETURN)
elif "Password:" in output:
+ assert self.password is not None
self.write_channel(self.password + self.RETURN)
break
time.sleep(delay_factor * 1)
@@ -653,9 +612,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RuckusFastironTelnet(RuckusFastironBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
- def _process_option(self, tsocket, command, option):
+ def _process_option(self, tsocket: socket, command: bytes, option: bytes) -> None:
"""
Ruckus FastIron/ICX does not always echo commands to output by default.
If server expresses interest in 'ECHO' option, then reply back with 'DO
@@ -398,8 +344,9 @@
Inherited members
elif command in (WILL, WONT):
tsocket.sendall(IAC + DONT + option)
- def telnet_login(self, *args, **kwargs):
+ def telnet_login(self, *args: Any, **kwargs: Any) -> str:
# set callback function to handle telnet options.
+ assert isinstance(self.remote_conn, Telnet)
self.remote_conn.set_option_negotiation_callback(self._process_option)
return super().telnet_login(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RuckusFastironBase(CiscoSSHConnection):
"""Ruckus FastIron aka ICX support."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""FastIron requires to be enable mode to disable paging."""
self._test_channel_read()
self.set_base_prompt()
@@ -283,8 +268,12 @@
Classes
self.clear_buffer()
def enable(
- self, cmd="enable", pattern=r"(ssword|User Name)", re_flags=re.IGNORECASE
- ):
+ self,
+ cmd: str = "enable",
+ pattern: str = r"(ssword|User Name)",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
"""Enter enable mode.
With RADIUS can prompt for User Name
SSH@Lab-ICX7250>en
@@ -299,23 +288,23 @@
Classes
while i < count:
self.write_channel(self.normalize_cmd(cmd))
new_data = self.read_until_prompt_or_pattern(
- pattern=pattern, re_flags=re_flags
+ pattern=pattern, re_flags=re_flags, read_entire_line=True
)
output += new_data
if "User Name" in new_data:
self.write_channel(self.normalize_cmd(self.username))
new_data = self.read_until_prompt_or_pattern(
- pattern=pattern, re_flags=re_flags
+ pattern=pattern, re_flags=re_flags, read_entire_line=True
)
output += new_data
if "ssword" in new_data:
self.write_channel(self.normalize_cmd(self.secret))
- new_data = self.read_until_prompt()
+ new_data = self.read_until_prompt(read_entire_line=True)
output += new_data
if not re.search(
r"error.*incorrect.*password", new_data, flags=re.I
):
- return output
+ break
time.sleep(1)
i += 1
@@ -327,7 +316,11 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RuckusFastironTelnet(RuckusFastironBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
- def _process_option(self, tsocket, command, option):
+ def _process_option(self, tsocket: socket, command: bytes, option: bytes) -> None:
"""
Ruckus FastIron/ICX does not always echo commands to output by default.
If server expresses interest in 'ECHO' option, then reply back with 'DO
@@ -837,8 +784,9 @@
Inherited members
elif command in (WILL, WONT):
tsocket.sendall(IAC + DONT + option)
- def telnet_login(self, *args, **kwargs):
+ def telnet_login(self, *args: Any, **kwargs: Any) -> str:
# set callback function to handle telnet options.
+ assert isinstance(self.remote_conn, Telnet)
self.remote_conn.set_option_negotiation_callback(self._process_option)
return super().telnet_login(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RuijieOSTelnet(RuijieOSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RuijieOSBase(CiscoBaseConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -220,7 +197,9 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -281,9 +262,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class RuijieOSTelnet(RuijieOSBase):
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
default_enter = kwargs.get("default_enter")
kwargs["default_enter"] = "\r\n" if default_enter is None else default_enter
super().__init__(*args, **kwargs)
print(msg)
-def verifyspace_and_transferfile(scp_transfer):
+def verifyspace_and_transferfile(scp_transfer: BaseFileTransfer) -> None:
"""Verify space and transfer file."""
if not scp_transfer.verify_space_available():
raise ValueError("Insufficient space available on remote device")
@@ -67,19 +78,19 @@
def verifyspace_and_transferfile(scp_transfer: BaseFileTransfer) -> None:
"""Verify space and transfer file."""
if not scp_transfer.verify_space_available():
raise ValueError("Insufficient space available on remote device")
diff --git a/docs/netmiko/scp_handler.html b/docs/netmiko/scp_handler.html
index 4a49cc433..83dd64efd 100644
--- a/docs/netmiko/scp_handler.html
+++ b/docs/netmiko/scp_handler.html
@@ -23,7 +23,6 @@
Module netmiko.scp_handler
Netmiko SCP operations.
Supports file get and file put operations.
SCP requires a separate SSH connection for a control channel.
-
Currently only supports Cisco IOS and Cisco ASA.
Source code
"""
@@ -32,15 +31,19 @@
Module netmiko.scp_handler
Supports file get and file put operations.
SCP requires a separate SSH connection for a control channel.
-
-Currently only supports Cisco IOS and Cisco ASA.
"""
+from typing import Callable, Optional, Any, Type
+from typing import TYPE_CHECKING
+from types import TracebackType
import re
import os
import hashlib
import scp
-import platform
+import sys
+
+if TYPE_CHECKING:
+ from netmiko.base_connection import BaseConnection
class SCPConn(object):
@@ -50,14 +53,20 @@
Module netmiko.scp_handler
Must close the SCP connection to get the file to write to the remote filesystem
"""
- def __init__(self, ssh_conn, socket_timeout=10.0, progress=None, progress4=None):
+ def __init__(
+ self,
+ ssh_conn: "BaseConnection",
+ socket_timeout: float = 10.0,
+ progress: Optional[Callable[..., Any]] = None,
+ progress4: Optional[Callable[..., Any]] = None,
+ ) -> None:
self.ssh_ctl_chan = ssh_conn
self.socket_timeout = socket_timeout
self.progress = progress
self.progress4 = progress4
self.establish_scp_conn()
- def establish_scp_conn(self):
+ def establish_scp_conn(self) -> None:
"""Establish the secure copy connection."""
ssh_connect_params = self.ssh_ctl_chan._connect_params_dict()
self.scp_conn = self.ssh_ctl_chan._build_ssh_client()
@@ -69,26 +78,19 @@
progress4=self.progress4,
)
- def close_scp_chan(self):
+ def close_scp_chan(self) -> None:
"""Close the SCP connection to the remote network device."""
self.scp_conn.close()
- self.scp_conn = None
+ del self.scp_conn
- def remote_space_available(self, search_pattern=r"(\d+) \w+ free"):
+ def remote_space_available(self, search_pattern: str = r"(\d+) \w+ free") -> int:
"""Return space available on remote device."""
remote_cmd = f"dir {self.file_system}"
- remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_output = self.ssh_ctl_chan._send_command_str(remote_cmd)
match = re.search(search_pattern, remote_output)
- if "kbytes" in match.group(0) or "Kbytes" in match.group(0):
- return int(match.group(1)) * 1000
- return int(match.group(1))
+ if match:
+ if "kbytes" in match.group(0) or "Kbytes" in match.group(0):
+ return int(match.group(1)) * 1000
+ return int(match.group(1))
+ else:
+ msg = (
+ f"pattern: {search_pattern} not detected in output:\n\n{remote_output}"
+ )
+ raise ValueError(msg)
- def _remote_space_available_unix(self, search_pattern=""):
+ def _remote_space_available_unix(self, search_pattern: str = "") -> int:
"""Return space available on *nix system (BSD/Linux)."""
self.ssh_ctl_chan._enter_shell()
remote_cmd = f"/bin/df -k {self.file_system}"
- remote_output = self.ssh_ctl_chan.send_command(
+ remote_output = self.ssh_ctl_chan._send_command_str(
remote_cmd, expect_string=r"[\$#]"
)
@@ -207,9 +220,9 @@
Module netmiko.scp_handler
self.ssh_ctl_chan._return_cli()
return int(space_available) * 1024
- def local_space_available(self):
+ def local_space_available(self) -> int:
"""Return space available on local filesystem."""
- if platform.system() == "Windows":
+ if sys.platform == "win32":
import ctypes
free_bytes = ctypes.c_ulonglong(0)
@@ -221,7 +234,7 @@
Module netmiko.scp_handler
destination_stats = os.statvfs(".")
return destination_stats.f_bsize * destination_stats.f_bavail
- def verify_space_available(self, search_pattern=r"(\d+) \w+ free"):
+ def verify_space_available(self, search_pattern: str = r"(\d+) \w+ free") -> bool:
"""Verify sufficient space is available on destination file system (return boolean)."""
if self.direction == "put":
space_avail = self.remote_space_available(search_pattern=search_pattern)
@@ -231,12 +244,12 @@
Module netmiko.scp_handler
return True
return False
- def check_file_exists(self, remote_cmd=""):
+ def check_file_exists(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = f"dir {self.file_system}/{self.dest_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
search_string = r"Directory of .*{0}".format(self.dest_file)
if (
"Error opening" in remote_out
@@ -250,21 +263,27 @@
Module netmiko.scp_handler
raise ValueError("Unexpected output from check_file_exists")
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def _check_file_exists_unix(self, remote_cmd=""):
+ def _check_file_exists_unix(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
self.ssh_ctl_chan._enter_shell()
- remote_cmd = f"ls {self.file_system}"
- remote_out = self.ssh_ctl_chan.send_command(
+ remote_cmd = f"/bin/ls {self.file_system}"
+ remote_out = self.ssh_ctl_chan._send_command_str(
remote_cmd, expect_string=r"[\$#]"
)
self.ssh_ctl_chan._return_cli()
return self.dest_file in remote_out
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_file_size(self, remote_cmd="", remote_file=None):
+ def remote_file_size(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -273,11 +292,12 @@
Module netmiko.scp_handler
remote_file = self.source_file
if not remote_cmd:
remote_cmd = f"dir {self.file_system}/{remote_file}"
- remote_out = self.ssh_ctl_chan.send_command(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
# Strip out "Directory of flash:/filename line
- remote_out = re.split(r"Directory of .*", remote_out)
- remote_out = "".join(remote_out)
+ remote_out_lines = re.split(r"Directory of .*", remote_out)
+ remote_out = "".join(remote_out_lines)
# Match line containing file name
+ assert isinstance(remote_file, str)
escape_file_name = re.escape(remote_file)
pattern = r".*({}).*".format(escape_file_name)
match = re.search(pattern, remote_out)
@@ -293,7 +313,9 @@
Module netmiko.scp_handler
else:
return int(file_size)
- def _remote_file_size_unix(self, remote_cmd="", remote_file=None):
+ def _remote_file_size_unix(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -302,10 +324,12 @@
Module netmiko.scp_handler
remote_file = self.source_file
remote_file = f"{self.file_system}/{remote_file}"
if not remote_cmd:
- remote_cmd = f"ls -l {remote_file}"
+ remote_cmd = f"/bin/ls -l {remote_file}"
self.ssh_ctl_chan._enter_shell()
- remote_out = self.ssh_ctl_chan.send_command(remote_cmd, expect_string=r"[\$#]")
+ remote_out = self.ssh_ctl_chan._send_command_str(
+ remote_cmd, expect_string=r"[\$#]"
+ )
self.ssh_ctl_chan._return_cli()
if "No such file or directory" in remote_out:
@@ -324,7 +348,7 @@
Module netmiko.scp_handler
"Search pattern not found for remote file size during SCP transfer."
)
- def file_md5(self, file_name, add_newline=False):
+ def file_md5(self, file_name: str, add_newline: bool = False) -> str:
"""Compute MD5 hash of file.
add_newline is needed to support Cisco IOS MD5 calculation which expects the newline in
@@ -347,7 +371,7 @@
Module netmiko.scp_handler
return file_hash.hexdigest()
@staticmethod
- def process_md5(md5_output, pattern=r"=\s+(\S+)"):
+ def process_md5(md5_output: str, pattern: str = r"=\s+(\S+)") -> str:
"""
Process the string to retrieve the MD5 hash
@@ -361,7 +385,7 @@
Module netmiko.scp_handler
else:
raise ValueError(f"Invalid output from MD5 command: {md5_output}")
- def compare_md5(self):
+ def compare_md5(self) -> bool:
"""Compare md5 of file on network device to md5 of local file."""
if self.direction == "put":
remote_md5 = self.remote_md5()
@@ -369,8 +393,12 @@
Module netmiko.scp_handler
elif self.direction == "get":
local_md5 = self.file_md5(self.dest_file)
return self.source_md5 == local_md5
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_md5(self, base_cmd="verify /md5", remote_file=None):
+ def remote_md5(
+ self, base_cmd: str = "verify /md5", remote_file: Optional[str] = None
+ ) -> str:
"""Calculate remote MD5 and returns the hash.
This command can be CPU intensive on the remote device.
@@ -381,56 +409,50 @@
Module netmiko.scp_handler
elif self.direction == "get":
remote_file = self.source_file
remote_md5_cmd = f"{base_cmd} {self.file_system}/{remote_file}"
- dest_md5 = self.ssh_ctl_chan.send_command(remote_md5_cmd, max_loops=1500)
+ dest_md5 = self.ssh_ctl_chan._send_command_str(remote_md5_cmd, read_timeout=300)
dest_md5 = self.process_md5(dest_md5)
return dest_md5
- def transfer_file(self):
+ def transfer_file(self) -> None:
"""SCP transfer file."""
if self.direction == "put":
self.put_file()
elif self.direction == "get":
self.get_file()
+ else:
+ raise ValueError("Unexpected value for self.direction in transfer_file")
- def get_file(self):
+ def get_file(self) -> None:
"""SCP copy the file from the remote device to local system."""
source_file = f"{self.file_system}/{self.source_file}"
self.scp_conn.scp_get_file(source_file, self.dest_file)
self.scp_conn.close()
- def put_file(self):
+ def put_file(self) -> None:
"""SCP copy the file from the local system to the remote device."""
destination = f"{self.file_system}/{self.dest_file}"
self.scp_conn.scp_transfer_file(self.source_file, destination)
# Must close the SCP connection to get the file written (flush)
self.scp_conn.close()
- def verify_file(self):
+ def verify_file(self) -> bool:
"""Verify the file has been transferred correctly."""
return self.compare_md5()
- def enable_scp(self, cmd=None):
+ def enable_scp(self, cmd: str = "ip scp server enable") -> None:
"""
Enable SCP on remote device.
Defaults to Cisco IOS command
"""
- if cmd is None:
- cmd = ["ip scp server enable"]
- elif not hasattr(cmd, "__iter__"):
- cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd)
- def disable_scp(self, cmd=None):
+ def disable_scp(self, cmd: str = "no ip scp server enable") -> None:
"""
Disable SCP on remote device.
Defaults to Cisco IOS command
"""
- if cmd is None:
- cmd = ["no ip scp server enable"]
- elif not hasattr(cmd, "__iter__"):
- cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd)
progress4=self.progress4,
)
- def close_scp_chan(self):
+ def close_scp_chan(self) -> None:
"""Close the SCP connection to the remote network device."""
self.scp_conn.close()
- self.scp_conn = None
+ del self.scp_conn
- def remote_space_available(self, search_pattern=r"(\d+) \w+ free"):
+ def remote_space_available(self, search_pattern: str = r"(\d+) \w+ free") -> int:
"""Return space available on remote device."""
remote_cmd = f"dir {self.file_system}"
- remote_output = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_output = self.ssh_ctl_chan._send_command_str(remote_cmd)
match = re.search(search_pattern, remote_output)
- if "kbytes" in match.group(0) or "Kbytes" in match.group(0):
- return int(match.group(1)) * 1000
- return int(match.group(1))
+ if match:
+ if "kbytes" in match.group(0) or "Kbytes" in match.group(0):
+ return int(match.group(1)) * 1000
+ return int(match.group(1))
+ else:
+ msg = (
+ f"pattern: {search_pattern} not detected in output:\n\n{remote_output}"
+ )
+ raise ValueError(msg)
- def _remote_space_available_unix(self, search_pattern=""):
+ def _remote_space_available_unix(self, search_pattern: str = "") -> int:
"""Return space available on *nix system (BSD/Linux)."""
self.ssh_ctl_chan._enter_shell()
remote_cmd = f"/bin/df -k {self.file_system}"
- remote_output = self.ssh_ctl_chan.send_command(
+ remote_output = self.ssh_ctl_chan._send_command_str(
remote_cmd, expect_string=r"[\$#]"
)
@@ -565,9 +598,9 @@
Classes
self.ssh_ctl_chan._return_cli()
return int(space_available) * 1024
- def local_space_available(self):
+ def local_space_available(self) -> int:
"""Return space available on local filesystem."""
- if platform.system() == "Windows":
+ if sys.platform == "win32":
import ctypes
free_bytes = ctypes.c_ulonglong(0)
@@ -579,7 +612,7 @@
Classes
destination_stats = os.statvfs(".")
return destination_stats.f_bsize * destination_stats.f_bavail
- def verify_space_available(self, search_pattern=r"(\d+) \w+ free"):
+ def verify_space_available(self, search_pattern: str = r"(\d+) \w+ free") -> bool:
"""Verify sufficient space is available on destination file system (return boolean)."""
if self.direction == "put":
space_avail = self.remote_space_available(search_pattern=search_pattern)
@@ -589,12 +622,12 @@
Classes
return True
return False
- def check_file_exists(self, remote_cmd=""):
+ def check_file_exists(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = f"dir {self.file_system}/{self.dest_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
search_string = r"Directory of .*{0}".format(self.dest_file)
if (
"Error opening" in remote_out
@@ -608,21 +641,27 @@
Classes
raise ValueError("Unexpected output from check_file_exists")
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def _check_file_exists_unix(self, remote_cmd=""):
+ def _check_file_exists_unix(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
self.ssh_ctl_chan._enter_shell()
- remote_cmd = f"ls {self.file_system}"
- remote_out = self.ssh_ctl_chan.send_command(
+ remote_cmd = f"/bin/ls {self.file_system}"
+ remote_out = self.ssh_ctl_chan._send_command_str(
remote_cmd, expect_string=r"[\$#]"
)
self.ssh_ctl_chan._return_cli()
return self.dest_file in remote_out
elif self.direction == "get":
return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_file_size(self, remote_cmd="", remote_file=None):
+ def remote_file_size(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -631,11 +670,12 @@
Classes
remote_file = self.source_file
if not remote_cmd:
remote_cmd = f"dir {self.file_system}/{remote_file}"
- remote_out = self.ssh_ctl_chan.send_command(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
# Strip out "Directory of flash:/filename line
- remote_out = re.split(r"Directory of .*", remote_out)
- remote_out = "".join(remote_out)
+ remote_out_lines = re.split(r"Directory of .*", remote_out)
+ remote_out = "".join(remote_out_lines)
# Match line containing file name
+ assert isinstance(remote_file, str)
escape_file_name = re.escape(remote_file)
pattern = r".*({}).*".format(escape_file_name)
match = re.search(pattern, remote_out)
@@ -651,7 +691,9 @@
Classes
else:
return int(file_size)
- def _remote_file_size_unix(self, remote_cmd="", remote_file=None):
+ def _remote_file_size_unix(
+ self, remote_cmd: str = "", remote_file: Optional[str] = None
+ ) -> int:
"""Get the file size of the remote file."""
if remote_file is None:
if self.direction == "put":
@@ -660,10 +702,12 @@
Classes
remote_file = self.source_file
remote_file = f"{self.file_system}/{remote_file}"
if not remote_cmd:
- remote_cmd = f"ls -l {remote_file}"
+ remote_cmd = f"/bin/ls -l {remote_file}"
self.ssh_ctl_chan._enter_shell()
- remote_out = self.ssh_ctl_chan.send_command(remote_cmd, expect_string=r"[\$#]")
+ remote_out = self.ssh_ctl_chan._send_command_str(
+ remote_cmd, expect_string=r"[\$#]"
+ )
self.ssh_ctl_chan._return_cli()
if "No such file or directory" in remote_out:
@@ -682,7 +726,7 @@
Classes
"Search pattern not found for remote file size during SCP transfer."
)
- def file_md5(self, file_name, add_newline=False):
+ def file_md5(self, file_name: str, add_newline: bool = False) -> str:
"""Compute MD5 hash of file.
add_newline is needed to support Cisco IOS MD5 calculation which expects the newline in
@@ -705,7 +749,7 @@
Classes
return file_hash.hexdigest()
@staticmethod
- def process_md5(md5_output, pattern=r"=\s+(\S+)"):
+ def process_md5(md5_output: str, pattern: str = r"=\s+(\S+)") -> str:
"""
Process the string to retrieve the MD5 hash
@@ -719,7 +763,7 @@
Classes
else:
raise ValueError(f"Invalid output from MD5 command: {md5_output}")
- def compare_md5(self):
+ def compare_md5(self) -> bool:
"""Compare md5 of file on network device to md5 of local file."""
if self.direction == "put":
remote_md5 = self.remote_md5()
@@ -727,8 +771,12 @@
Classes
elif self.direction == "get":
local_md5 = self.file_md5(self.dest_file)
return self.source_md5 == local_md5
+ else:
+ raise ValueError("Unexpected value for self.direction")
- def remote_md5(self, base_cmd="verify /md5", remote_file=None):
+ def remote_md5(
+ self, base_cmd: str = "verify /md5", remote_file: Optional[str] = None
+ ) -> str:
"""Calculate remote MD5 and returns the hash.
This command can be CPU intensive on the remote device.
@@ -739,56 +787,50 @@
Classes
elif self.direction == "get":
remote_file = self.source_file
remote_md5_cmd = f"{base_cmd} {self.file_system}/{remote_file}"
- dest_md5 = self.ssh_ctl_chan.send_command(remote_md5_cmd, max_loops=1500)
+ dest_md5 = self.ssh_ctl_chan._send_command_str(remote_md5_cmd, read_timeout=300)
dest_md5 = self.process_md5(dest_md5)
return dest_md5
- def transfer_file(self):
+ def transfer_file(self) -> None:
"""SCP transfer file."""
if self.direction == "put":
self.put_file()
elif self.direction == "get":
self.get_file()
+ else:
+ raise ValueError("Unexpected value for self.direction in transfer_file")
- def get_file(self):
+ def get_file(self) -> None:
"""SCP copy the file from the remote device to local system."""
source_file = f"{self.file_system}/{self.source_file}"
self.scp_conn.scp_get_file(source_file, self.dest_file)
self.scp_conn.close()
- def put_file(self):
+ def put_file(self) -> None:
"""SCP copy the file from the local system to the remote device."""
destination = f"{self.file_system}/{self.dest_file}"
self.scp_conn.scp_transfer_file(self.source_file, destination)
# Must close the SCP connection to get the file written (flush)
self.scp_conn.close()
- def verify_file(self):
+ def verify_file(self) -> bool:
"""Verify the file has been transferred correctly."""
return self.compare_md5()
- def enable_scp(self, cmd=None):
+ def enable_scp(self, cmd: str = "ip scp server enable") -> None:
"""
Enable SCP on remote device.
Defaults to Cisco IOS command
"""
- if cmd is None:
- cmd = ["ip scp server enable"]
- elif not hasattr(cmd, "__iter__"):
- cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd)
- def disable_scp(self, cmd=None):
+ def disable_scp(self, cmd: str = "no ip scp server enable") -> None:
"""
Disable SCP on remote device.
Defaults to Cisco IOS command
"""
- if cmd is None:
- cmd = ["no ip scp server enable"]
- elif not hasattr(cmd, "__iter__"):
- cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd)
@staticmethod
-def process_md5(md5_output, pattern=r"=\s+(\S+)"):
+def process_md5(md5_output: str, pattern: str = r"=\s+(\S+)") -> str:
"""
Process the string to retrieve the MD5 hash
@@ -837,12 +880,12 @@
Methods
Check if the dest_file already exists on the file system (return boolean).
Source code
-
def check_file_exists(self, remote_cmd=""):
+
def check_file_exists(self, remote_cmd: str = "") -> bool:
"""Check if the dest_file already exists on the file system (return boolean)."""
if self.direction == "put":
if not remote_cmd:
remote_cmd = f"dir {self.file_system}/{self.dest_file}"
- remote_out = self.ssh_ctl_chan.send_command_expect(remote_cmd)
+ remote_out = self.ssh_ctl_chan._send_command_str(remote_cmd)
search_string = r"Directory of .*{0}".format(self.dest_file)
if (
"Error opening" in remote_out
@@ -855,7 +898,9 @@
+ return os.path.exists(self.dest_file)
+ else:
+ raise ValueError("Unexpected value for self.direction")
@@ -865,10 +910,10 @@
Methods
Close the SCP connection to the remote network device.
Source code
-
def close_scp_chan(self):
+
def close_scp_chan(self) -> None:
"""Close the SCP connection to the remote network device."""
self.scp_conn.close()
- self.scp_conn = None
+ del self.scp_conn
@@ -878,55 +923,49 @@
Methods
Compare md5 of file on network device to md5 of local file.
Source code
-
def compare_md5(self):
+
def compare_md5(self) -> bool:
"""Compare md5 of file on network device to md5 of local file."""
if self.direction == "put":
remote_md5 = self.remote_md5()
return self.source_md5 == remote_md5
elif self.direction == "get":
local_md5 = self.file_md5(self.dest_file)
- return self.source_md5 == local_md5
+ return self.source_md5 == local_md5
+ else:
+ raise ValueError("Unexpected value for self.direction")
-def disable_scp(self, cmd=None)
+def disable_scp(self, cmd='no ip scp server enable')
Disable SCP on remote device.
Defaults to Cisco IOS command
Source code
-
def disable_scp(self, cmd=None):
+
def disable_scp(self, cmd: str = "no ip scp server enable") -> None:
"""
Disable SCP on remote device.
Defaults to Cisco IOS command
"""
- if cmd is None:
- cmd = ["no ip scp server enable"]
- elif not hasattr(cmd, "__iter__"):
- cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd)
-def enable_scp(self, cmd=None)
+def enable_scp(self, cmd='ip scp server enable')
Enable SCP on remote device.
Defaults to Cisco IOS command
Source code
-
def enable_scp(self, cmd=None):
+
def enable_scp(self, cmd: str = "ip scp server enable") -> None:
"""
Enable SCP on remote device.
Defaults to Cisco IOS command
"""
- if cmd is None:
- cmd = ["ip scp server enable"]
- elif not hasattr(cmd, "__iter__"):
- cmd = [cmd]
self.ssh_ctl_chan.send_config_set(cmd)
def file_md5(self, file_name: str, add_newline: bool = False) -> str:
"""Compute MD5 hash of file.
add_newline is needed to support Cisco IOS MD5 calculation which expects the newline in
@@ -993,7 +1032,7 @@
Args
SCP copy the file from the remote device to local system.
Source code
-
def get_file(self):
+
def get_file(self) -> None:
"""SCP copy the file from the remote device to local system."""
source_file = f"{self.file_system}/{self.source_file}"
self.scp_conn.scp_get_file(source_file, self.dest_file)
@@ -1007,9 +1046,9 @@
Args
Return space available on local filesystem.
Source code
-
def local_space_available(self):
+
def local_space_available(self) -> int:
"""Return space available on local filesystem."""
- if platform.system() == "Windows":
+ if sys.platform == "win32":
import ctypes
free_bytes = ctypes.c_ulonglong(0)
@@ -1029,7 +1068,7 @@
Args
SCP copy the file from the local system to the remote device.
Source code
-
def put_file(self):
+
def put_file(self) -> None:
"""SCP copy the file from the local system to the remote device."""
destination = f"{self.file_system}/{self.dest_file}"
self.scp_conn.scp_transfer_file(self.source_file, destination)
@@ -1044,7 +1083,9 @@
def remote_md5(
+ self, base_cmd: str = "verify /md5", remote_file: Optional[str] = None
+) -> str:
"""Calculate remote MD5 and returns the hash.
This command can be CPU intensive on the remote device.
@@ -1093,7 +1137,7 @@
class SessionLog:
+ def __init__(
+ self,
+ file_name: Optional[str] = None,
+ buffered_io: Optional[io.BufferedIOBase] = None,
+ file_mode: str = "write",
+ file_encoding: str = "utf-8",
+ no_log: Dict[str, Any] = None,
+ record_writes: bool = False,
+ ) -> None:
+ if no_log is None:
+ self.no_log = {}
+ else:
+ self.no_log = no_log
+ self.file_name = file_name
+ self.file_mode = file_mode
+ self.file_encoding = file_encoding
+ self.record_writes = record_writes
+ self._session_log_close = False
+
+ # Actual file/file-handle/buffered-IO that will be written to.
+ self.session_log: Union[io.BufferedIOBase, TextIO, None]
+ if file_name is None and buffered_io:
+ self.session_log = buffered_io
+ else:
+ self.session_log = None
+
+ # Ensures last write operations prior to disconnect are recorded.
+ self.fin = False
+
+ def open(self) -> None:
+ """Open the session_log file."""
+ if self.file_name is None:
+ return None
+ if self.file_mode == "append":
+ self.session_log = open(
+ self.file_name, mode="a", encoding=self.file_encoding
+ )
+ else:
+ self.session_log = open(
+ self.file_name, mode="w", encoding=self.file_encoding
+ )
+ self._session_log_close = True
+
+ def close(self) -> None:
+ """Close the session_log file (if it is a file that we opened)."""
+ if self.session_log and self._session_log_close:
+ self.session_log.close()
+ self.session_log = None
+
+ def write(self, data: str) -> None:
+ if self.session_log is not None and len(data) > 0:
+ # Hide the password and secret in the session_log
+ for hidden_data in self.no_log.values():
+ data = data.replace(hidden_data, "********")
+
+ if isinstance(self.session_log, io.BufferedIOBase):
+ self.session_log.write(write_bytes(data, encoding=self.file_encoding))
+ else:
+ self.session_log.write(data)
+
+ assert isinstance(self.session_log, io.BufferedIOBase) or isinstance(
+ self.session_log, io.TextIOBase
+ )
+ self.session_log.flush()
+
+
Methods
+
+
+def close(self)
+
+
+
Close the session_log file (if it is a file that we opened).
+
+Source code
+
def close(self) -> None:
+ """Close the session_log file (if it is a file that we opened)."""
+ if self.session_log and self._session_log_close:
+ self.session_log.close()
+ self.session_log = None
def write(self, data: str) -> None:
+ if self.session_log is not None and len(data) > 0:
+ # Hide the password and secret in the session_log
+ for hidden_data in self.no_log.values():
+ data = data.replace(hidden_data, "********")
+
+ if isinstance(self.session_log, io.BufferedIOBase):
+ self.session_log.write(write_bytes(data, encoding=self.file_encoding))
+ else:
+ self.session_log.write(data)
+
+ assert isinstance(self.session_log, io.BufferedIOBase) or isinstance(
+ self.session_log, io.TextIOBase
+ )
+ self.session_log.flush()
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/netmiko/sixwind/index.html b/docs/netmiko/sixwind/index.html
index e4fd355a5..68802591d 100644
--- a/docs/netmiko/sixwind/index.html
+++ b/docs/netmiko/sixwind/index.html
@@ -45,139 +45,119 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class SixwindOSBase(CiscoBaseConnection):
- def session_preparation(self):
+
class SixwindOSBase(NoEnable, CiscoBaseConnection):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
self._test_channel_read()
@@ -282,46 +271,63 @@
Classes
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def disable_paging(self, *args, **kwargs):
+ def disable_paging(self, *args: Any, **kwargs: Any) -> str:
"""6WIND requires no-pager at the end of command, not implemented at this time."""
pass
def set_base_prompt(
- self, pri_prompt_terminator=">", alt_prompt_terminator="#", delay_factor=1
- ):
+ self,
+ pri_prompt_terminator: str = ">",
+ alt_prompt_terminator: str = "#",
+ delay_factor: float = 1.0,
+ pattern: Optional[str] = None,
+ ) -> str:
"""Sets self.base_prompt: used as delimiter for stripping of trailing prompt in output."""
prompt = super().set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor,
+ pattern=pattern,
)
prompt = prompt.strip()
self.base_prompt = prompt
return self.base_prompt
- def config_mode(self, config_command="edit running", pattern=""):
- """Enter configuration mode."""
-
- return super().config_mode(config_command=config_command, pattern=pattern)
+ def config_mode(
+ self, config_command: str = "edit running", pattern: str = "", re_flags: int = 0
+ ) -> str:
+ return super().config_mode(
+ config_command=config_command, pattern=pattern, re_flags=re_flags
+ )
- def commit(self, comment="", delay_factor=1):
+ def commit(
+ self,
+ comment: str = "",
+ read_timeout: float = 120.0,
+ delay_factor: Optional[float] = None,
+ ) -> str:
"""
Commit the candidate configuration.
Raise an error and return the failure if the commit fails.
+
+ delay_factor: Deprecated in Netmiko 4.x. Will be eliminated in Netmiko 5.
+
"""
- delay_factor = self.select_delay_factor(delay_factor)
+ if delay_factor is not None:
+ warnings.warn(DELAY_FACTOR_DEPR_SIMPLE_MSG, DeprecationWarning)
+
error_marker = "Failed to generate committed config"
command_string = "commit"
output = self.config_mode()
- output += self.send_command(
+ output += self._send_command_str(
command_string,
strip_prompt=False,
strip_command=False,
- delay_factor=delay_factor,
+ read_timeout=read_timeout,
expect_string=r"#",
)
output += self.exit_config_mode()
@@ -331,42 +337,31 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self.ansi_escape_codes = True
self._test_channel_read()
@@ -536,21 +493,26 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Note, pysnmp is a required dependency for SNMPDetect and is intentionally not included in
netmiko requirements. So installation of pysnmp might be required.
"""
+from typing import Optional, Dict
+from typing.re import Pattern
import re
try:
@@ -145,6 +147,11 @@
self.encrypt_key = encrypt_key
self.auth_proto = self._snmp_v3_authentication[auth_proto]
self.encryp_proto = self._snmp_v3_encryption[encrypt_proto]
- self._response_cache = {}
+ self._response_cache: Dict[str, str] = {}
- def _get_snmpv3(self, oid):
+ def _get_snmpv3(self, oid: str) -> str:
"""
Try to send an SNMP GET operation using SNMPv3 for the specified OID.
@@ -305,7 +311,7 @@
Example:
return str(snmp_data[0][1])
return ""
- def _get_snmpv2c(self, oid):
+ def _get_snmpv2c(self, oid: str) -> str:
"""
Try to send an SNMP GET operation using SNMPv2 for the specified OID.
@@ -334,14 +340,14 @@
Example:
return str(snmp_data[0][1])
return ""
- def _get_snmp(self, oid):
+ def _get_snmp(self, oid: str) -> str:
"""Wrapper for generic SNMP call."""
if self.snmp_version in ["v1", "v2c"]:
return self._get_snmpv2c(oid)
else:
return self._get_snmpv3(oid)
- def autodetect(self):
+ def autodetect(self) -> Optional[str]:
"""
Try to guess the device_type using SNMP GET based on the SNMP_MAPPER dict. The type which
is returned is directly matching the name in *netmiko.ssh_dispatcher.CLASS_MAPPER_BASE*
@@ -355,18 +361,18 @@
Example:
The name of the device_type that must be running.
"""
# Convert SNMP_MAPPER to a list and sort by priority
- snmp_mapper_list = []
+ snmp_mapper_orig = []
for k, v in SNMP_MAPPER.items():
- snmp_mapper_list.append({k: v})
+ snmp_mapper_orig.append({k: v})
snmp_mapper_list = sorted(
- snmp_mapper_list, key=lambda x: list(x.values())[0]["priority"]
+ snmp_mapper_orig, key=lambda x: list(x.values())[0]["priority"] # type: ignore
)
snmp_mapper_list.reverse()
for entry in snmp_mapper_list:
for device_type, v in entry.items():
- oid = v["oid"]
- regex = v["expr"]
+ oid: str = v["oid"] # type: ignore
+ regex: Pattern = v["expr"]
# Used cache data if we already queryied this OID
if self._response_cache.get(oid):
@@ -377,6 +383,7 @@
Example:
# See if we had a match
if re.search(regex, snmp_response):
+ assert isinstance(device_type, str)
return device_type
return None
self.encrypt_key = encrypt_key
self.auth_proto = self._snmp_v3_authentication[auth_proto]
self.encryp_proto = self._snmp_v3_encryption[encrypt_proto]
- self._response_cache = {}
+ self._response_cache: Dict[str, str] = {}
- def _get_snmpv3(self, oid):
+ def _get_snmpv3(self, oid: str) -> str:
"""
Try to send an SNMP GET operation using SNMPv3 for the specified OID.
@@ -595,7 +601,7 @@
Methods
return str(snmp_data[0][1])
return ""
- def _get_snmpv2c(self, oid):
+ def _get_snmpv2c(self, oid: str) -> str:
"""
Try to send an SNMP GET operation using SNMPv2 for the specified OID.
@@ -624,14 +630,14 @@
Methods
return str(snmp_data[0][1])
return ""
- def _get_snmp(self, oid):
+ def _get_snmp(self, oid: str) -> str:
"""Wrapper for generic SNMP call."""
if self.snmp_version in ["v1", "v2c"]:
return self._get_snmpv2c(oid)
else:
return self._get_snmpv3(oid)
- def autodetect(self):
+ def autodetect(self) -> Optional[str]:
"""
Try to guess the device_type using SNMP GET based on the SNMP_MAPPER dict. The type which
is returned is directly matching the name in *netmiko.ssh_dispatcher.CLASS_MAPPER_BASE*
@@ -645,18 +651,18 @@
Methods
The name of the device_type that must be running.
"""
# Convert SNMP_MAPPER to a list and sort by priority
- snmp_mapper_list = []
+ snmp_mapper_orig = []
for k, v in SNMP_MAPPER.items():
- snmp_mapper_list.append({k: v})
+ snmp_mapper_orig.append({k: v})
snmp_mapper_list = sorted(
- snmp_mapper_list, key=lambda x: list(x.values())[0]["priority"]
+ snmp_mapper_orig, key=lambda x: list(x.values())[0]["priority"] # type: ignore
)
snmp_mapper_list.reverse()
for entry in snmp_mapper_list:
for device_type, v in entry.items():
- oid = v["oid"]
- regex = v["expr"]
+ oid: str = v["oid"] # type: ignore
+ regex: Pattern = v["expr"]
# Used cache data if we already queryied this OID
if self._response_cache.get(oid):
@@ -667,6 +673,7 @@
Methods
# See if we had a match
if re.search(regex, snmp_response):
+ assert isinstance(device_type, str)
return device_type
return None
@@ -688,7 +695,7 @@
Returns
Source code
-
def autodetect(self):
+
def autodetect(self) -> Optional[str]:
"""
Try to guess the device_type using SNMP GET based on the SNMP_MAPPER dict. The type which
is returned is directly matching the name in *netmiko.ssh_dispatcher.CLASS_MAPPER_BASE*
@@ -702,18 +709,18 @@
Returns
The name of the device_type that must be running.
"""
# Convert SNMP_MAPPER to a list and sort by priority
- snmp_mapper_list = []
+ snmp_mapper_orig = []
for k, v in SNMP_MAPPER.items():
- snmp_mapper_list.append({k: v})
+ snmp_mapper_orig.append({k: v})
snmp_mapper_list = sorted(
- snmp_mapper_list, key=lambda x: list(x.values())[0]["priority"]
+ snmp_mapper_orig, key=lambda x: list(x.values())[0]["priority"] # type: ignore
)
snmp_mapper_list.reverse()
for entry in snmp_mapper_list:
for device_type, v in entry.items():
- oid = v["oid"]
- regex = v["expr"]
+ oid: str = v["oid"] # type: ignore
+ regex: Pattern = v["expr"]
# Used cache data if we already queryied this OID
if self._response_cache.get(oid):
@@ -724,6 +731,7 @@
Returns
# See if we had a match
if re.search(regex, snmp_response):
+ assert isinstance(device_type, str)
return device_type
return None
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class SophosSfosSSH(CiscoSSHConnection):
- def session_preparation(self):
+
class SophosSfosSSH(NoEnable, NoConfig, CiscoSSHConnection):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
"""
@@ -208,114 +188,20 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
"""
@@ -367,20 +253,25 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class SophosSfosSSH(CiscoSSHConnection):
- def session_preparation(self):
+
class SophosSfosSSH(NoEnable, NoConfig, CiscoSSHConnection):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
"""
@@ -258,114 +218,20 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
"""
@@ -417,20 +283,25 @@
Netmiko connection creation section
# 'dispatch' key is the SSHDetect method to call. dispatch key will be popped off dictionary
# remaining keys indicate kwargs that will be passed to dispatch method.
# Note, the 'cmd' needs to avoid output paging.
-SSH_MAPPER_BASE = {
+SSH_MAPPER_DICT = {
"alcatel_aos": {
"cmd": "show system",
"search_patterns": [r"Alcatel-Lucent"],
@@ -133,6 +137,12 @@
Netmiko connection creation section
},
}
-# Sort SSH_MAPPER_BASE such that the most common commands are first
-cmd_count = {}
-for k, v in SSH_MAPPER_BASE.items():
- count = cmd_count.setdefault(v["cmd"], 0)
- cmd_count[v["cmd"]] = count + 1
+# Sort SSH_MAPPER_DICT such that the most common commands are first
+cmd_count: Dict[str, int] = {}
+for k, v in SSH_MAPPER_DICT.items():
+ my_cmd = v["cmd"]
+ assert isinstance(my_cmd, str)
+ count = cmd_count.setdefault(my_cmd, 0)
+ cmd_count[my_cmd] = count + 1
cmd_count = {k: v for k, v in sorted(cmd_count.items(), key=lambda item: item[1])}
-# SSH_MAPPER_BASE will be a list after this
+# SSH_MAPPER_BASE is a list
SSH_MAPPER_BASE = sorted(
- SSH_MAPPER_BASE.items(), key=lambda item: int(cmd_count[item[1]["cmd"]])
+ SSH_MAPPER_DICT.items(), key=lambda item: int(cmd_count[str(item[1]["cmd"])])
)
SSH_MAPPER_BASE.reverse()
@@ -328,7 +358,7 @@
Netmiko connection creation section
Try to determine the device type.
"""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Constructor of the SSHDetect class
"""
@@ -340,10 +370,10 @@
Netmiko connection creation section
# Call the _test_channel_read() in base to clear initial data
output = BaseConnection._test_channel_read(self.connection)
self.initial_buffer = output
- self.potential_matches = {}
- self._results_cache = {}
+ self.potential_matches: Dict[str, int] = {}
+ self._results_cache: Dict[str, str] = {}
- def autodetect(self):
+ def autodetect(self) -> Union[str, None]:
"""
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
@@ -355,6 +385,7 @@
Netmiko connection creation section
best_match = sorted(
self.potential_matches.items(), key=lambda t: t[1], reverse=True
)
+ # WLC needs two different auto-dectect solutions
+ if "cisco_wlc_85" in best_match[0]:
+ best_match[0] = ("cisco_wlc", 99)
+
self.connection.disconnect()
return best_match[0][0]
@@ -376,7 +411,7 @@
Netmiko connection creation section
self.connection.disconnect()
return best_match[0][0]
- def _send_command(self, cmd=""):
+ def _send_command(self, cmd: str = "") -> str:
"""
Handle reading/writing channel directly. It is also sanitizing the output received.
@@ -392,11 +427,11 @@
Netmiko connection creation section
"""
self.connection.write_channel(cmd + "\n")
time.sleep(1)
- output = self.connection._read_channel_timing()
+ output = self.connection.read_channel_timing()
output = self.connection.strip_backspaces(output)
return output
- def _send_command_wrapper(self, cmd):
+ def _send_command_wrapper(self, cmd: str) -> str:
"""
Send command to the remote device with a caching feature to avoid sending the same command
twice based on the SSH_MAPPER_BASE dict cmd key.
@@ -420,8 +455,12 @@
Netmiko connection creation section
return cached_results
def _autodetect_remote_version(
- self, search_patterns=None, re_flags=re.IGNORECASE, priority=99, **kwargs
- ):
+ self,
+ search_patterns: Optional[List[str]] = None,
+ re_flags: int = re.IGNORECASE,
+ priority: int = 99,
+ **kwargs: Any
+ ) -> int:
"""
Method to try auto-detect the device type, by matching a regular expression on the reported
remote version of the SSH server.
@@ -442,7 +481,10 @@
Netmiko connection creation section
return 0
try:
- remote_version = self.connection.remote_conn.transport.remote_version
+ remote_conn = self.connection.remote_conn
+ assert isinstance(remote_conn, paramiko.Channel)
+ assert remote_conn.transport is not None
+ remote_version = remote_conn.transport.remote_version
for pattern in invalid_responses:
match = re.search(pattern, remote_version, flags=re.I)
if match:
@@ -456,8 +498,12 @@
Netmiko connection creation section
return 0
def _autodetect_std(
- self, cmd="", search_patterns=None, re_flags=re.IGNORECASE, priority=99
- ):
+ self,
+ cmd: str = "",
+ search_patterns: Optional[List[str]] = None,
+ re_flags: int = re.IGNORECASE,
+ priority: int = 99,
+ ) -> int:
"""
Standard method to try to auto-detect the device type. This method will be called for each
device_type present in SSH_MAPPER_BASE dict ('dispatch' key). It will attempt to send a
@@ -482,6 +528,7 @@
Netmiko connection creation section
r"%Error",
r"command not found",
r"Syntax Error: unexpected argument",
+ r"% Unrecognized command found at",
]
if not cmd or not search_patterns:
return 0
@@ -567,7 +614,7 @@
Methods
Try to determine the device type.
"""
- def __init__(self, *args, **kwargs):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Constructor of the SSHDetect class
"""
@@ -579,10 +626,10 @@
Methods
# Call the _test_channel_read() in base to clear initial data
output = BaseConnection._test_channel_read(self.connection)
self.initial_buffer = output
- self.potential_matches = {}
- self._results_cache = {}
+ self.potential_matches: Dict[str, int] = {}
+ self._results_cache: Dict[str, str] = {}
- def autodetect(self):
+ def autodetect(self) -> Union[str, None]:
"""
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
@@ -594,6 +641,7 @@
Methods
for device_type, autodetect_dict in SSH_MAPPER_BASE:
tmp_dict = autodetect_dict.copy()
call_method = tmp_dict.pop("dispatch")
+ assert isinstance(call_method, str)
autodetect_method = getattr(self, call_method)
accuracy = autodetect_method(**tmp_dict)
if accuracy:
@@ -602,6 +650,10 @@
Methods
best_match = sorted(
self.potential_matches.items(), key=lambda t: t[1], reverse=True
)
+ # WLC needs two different auto-dectect solutions
+ if "cisco_wlc_85" in best_match[0]:
+ best_match[0] = ("cisco_wlc", 99)
+
self.connection.disconnect()
return best_match[0][0]
@@ -615,7 +667,7 @@
Methods
self.connection.disconnect()
return best_match[0][0]
- def _send_command(self, cmd=""):
+ def _send_command(self, cmd: str = "") -> str:
"""
Handle reading/writing channel directly. It is also sanitizing the output received.
@@ -631,11 +683,11 @@
Methods
"""
self.connection.write_channel(cmd + "\n")
time.sleep(1)
- output = self.connection._read_channel_timing()
+ output = self.connection.read_channel_timing()
output = self.connection.strip_backspaces(output)
return output
- def _send_command_wrapper(self, cmd):
+ def _send_command_wrapper(self, cmd: str) -> str:
"""
Send command to the remote device with a caching feature to avoid sending the same command
twice based on the SSH_MAPPER_BASE dict cmd key.
@@ -659,8 +711,12 @@
Methods
return cached_results
def _autodetect_remote_version(
- self, search_patterns=None, re_flags=re.IGNORECASE, priority=99, **kwargs
- ):
+ self,
+ search_patterns: Optional[List[str]] = None,
+ re_flags: int = re.IGNORECASE,
+ priority: int = 99,
+ **kwargs: Any
+ ) -> int:
"""
Method to try auto-detect the device type, by matching a regular expression on the reported
remote version of the SSH server.
@@ -681,7 +737,10 @@
Methods
return 0
try:
- remote_version = self.connection.remote_conn.transport.remote_version
+ remote_conn = self.connection.remote_conn
+ assert isinstance(remote_conn, paramiko.Channel)
+ assert remote_conn.transport is not None
+ remote_version = remote_conn.transport.remote_version
for pattern in invalid_responses:
match = re.search(pattern, remote_version, flags=re.I)
if match:
@@ -695,8 +754,12 @@
Methods
return 0
def _autodetect_std(
- self, cmd="", search_patterns=None, re_flags=re.IGNORECASE, priority=99
- ):
+ self,
+ cmd: str = "",
+ search_patterns: Optional[List[str]] = None,
+ re_flags: int = re.IGNORECASE,
+ priority: int = 99,
+ ) -> int:
"""
Standard method to try to auto-detect the device type. This method will be called for each
device_type present in SSH_MAPPER_BASE dict ('dispatch' key). It will attempt to send a
@@ -721,6 +784,7 @@
Methods
r"%Error",
r"command not found",
r"Syntax Error: unexpected argument",
+ r"% Unrecognized command found at",
]
if not cmd or not search_patterns:
return 0
@@ -754,7 +818,7 @@
Returns
Source code
-
def autodetect(self):
+
def autodetect(self) -> Union[str, None]:
"""
Try to guess the best 'device_type' based on patterns defined in SSH_MAPPER_BASE
@@ -766,6 +830,7 @@
Returns
for device_type, autodetect_dict in SSH_MAPPER_BASE:
tmp_dict = autodetect_dict.copy()
call_method = tmp_dict.pop("dispatch")
+ assert isinstance(call_method, str)
autodetect_method = getattr(self, call_method)
accuracy = autodetect_method(**tmp_dict)
if accuracy:
@@ -774,6 +839,10 @@
Returns
best_match = sorted(
self.potential_matches.items(), key=lambda t: t[1], reverse=True
)
+ # WLC needs two different auto-dectect solutions
+ if "cisco_wlc_85" in best_match[0]:
+ best_match[0] = ("cisco_wlc", 99)
+
self.connection.disconnect()
return best_match[0][0]
diff --git a/docs/netmiko/supermicro/index.html b/docs/netmiko/supermicro/index.html
index a95c7ef44..2e888cb54 100644
--- a/docs/netmiko/supermicro/index.html
+++ b/docs/netmiko/supermicro/index.html
@@ -45,139 +45,119 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class SmciSwitchSmisBase(CiscoBaseConnection):
- def session_preparation(self):
+
class SmciSwitchSmisBase(NoEnable, CiscoBaseConnection):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -228,21 +204,16 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -329,20 +280,21 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class TerminalServerTelnet(TerminalServer):
"""Generic Terminal Server driver telnet."""
- def telnet_login(self, *args, **kwargs):
+ def telnet_login(self, *args: Any, **kwargs: Any) -> str:
# Disable automatic handling of username and password when using terminal server driver
pass
- def std_login(self, *args, **kwargs):
+ def std_login(self, *args: Any, **kwargs: Any) -> str:
return super().telnet_login(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -212,7 +187,7 @@
Classes
an exception.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Do nothing here; base_prompt is not set; paging is not disabled."""
pass
@@ -234,7 +209,7 @@
Methods
Do nothing here; base_prompt is not set; paging is not disabled.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Do nothing here; base_prompt is not set; paging is not disabled."""
pass
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class TerminalServerTelnet(TerminalServer):
"""Generic Terminal Server driver telnet."""
- def telnet_login(self, *args, **kwargs):
+ def telnet_login(self, *args: Any, **kwargs: Any) -> str:
# Disable automatic handling of username and password when using terminal server driver
pass
- def std_login(self, *args, **kwargs):
+ def std_login(self, *args: Any, **kwargs: Any) -> str:
return super().telnet_login(*args, **kwargs)
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
import re
import time
+from typing import Any, Optional
from cryptography.hazmat.primitives.asymmetric import dsa
+from cryptography.hazmat.primitives.asymmetric.dsa import DSAParameterNumbers
from netmiko import log
from netmiko.cisco_base_connection import CiscoSSHConnection
-from netmiko.ssh_exception import NetmikoTimeoutException
+from netmiko.exceptions import NetmikoTimeoutException
class TPLinkJetStreamBase(CiscoSSHConnection):
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# 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
@@ -42,7 +44,7 @@
Module netmiko.tplink.tplink_jetstream
kwargs["default_enter"] = "\r\n"
return super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
"""
@@ -57,7 +59,13 @@
Module netmiko.tplink.tplink_jetstream
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def enable(self, cmd="", pattern="ssword", re_flags=re.IGNORECASE):
+ def enable(
+ self,
+ cmd: str = "",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
"""
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
@@ -82,21 +90,24 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class TPLinkJetStreamBase(CiscoSSHConnection):
- def __init__(self, **kwargs):
+ def __init__(self, **kwargs: Any) -> None:
# 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
@@ -355,7 +345,7 @@
Classes
kwargs["default_enter"] = "\r\n"
return super().__init__(**kwargs)
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
"""
@@ -370,7 +360,13 @@
Classes
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def enable(self, cmd="", pattern="ssword", re_flags=re.IGNORECASE):
+ def enable(
+ self,
+ cmd: str = "",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+ ) -> str:
"""
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
@@ -395,21 +391,24 @@
def enable(
+ self,
+ cmd: str = "",
+ pattern: str = "ssword",
+ enable_pattern: Optional[str] = None,
+ re_flags: int = re.IGNORECASE,
+) -> str:
"""
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
@@ -530,10 +532,10 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Implements support for Ubiquity EdgeSwitch devices.
@@ -91,131 +100,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -228,7 +210,7 @@
Classes
This is NOT for EdgeRouter devices.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
self._test_channel_read()
self.set_base_prompt()
self.enable()
@@ -240,23 +222,32 @@
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string=")#"):
+
def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
- return super().check_config_mode(check_string=check_string)
class UbiquitiEdgeRouterSSH(VyOSSSH):
"""Implement methods for interacting with EdgeOS EdgeRouter network devices."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -39,11 +39,13 @@
Module netmiko.ubiquiti.edgerouter_ssh
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def save_config(self, cmd="save", confirm=False, confirm_response=""):
+ def save_config(
+ self, cmd: str = "save", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Saves Config."""
if confirm is True:
raise ValueError("EdgeRouter does not support save_config confirmation.")
- output = self.send_command(command_string=cmd)
+ output = self._send_command_str(command_string=cmd)
if "Done" not in output:
raise ValueError(f"Save failed with following errors:\n\n{output}")
return output
Implement methods for interacting with EdgeOS EdgeRouter network devices.
@@ -68,138 +70,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class UbiquitiEdgeRouterSSH(VyOSSSH):
"""Implement methods for interacting with EdgeOS EdgeRouter network devices."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -209,11 +184,13 @@
Classes
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def save_config(self, cmd="save", confirm=False, confirm_response=""):
+ def save_config(
+ self, cmd: str = "save", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Saves Config."""
if confirm is True:
raise ValueError("EdgeRouter does not support save_config confirmation.")
- output = self.send_command(command_string=cmd)
+ output = self._send_command_str(command_string=cmd)
if "Done" not in output:
raise ValueError(f"Save failed with following errors:\n\n{output}")
return output
Implement methods for interacting with EdgeOS EdgeRouter network devices.
@@ -68,138 +67,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class UbiquitiEdgeRouterSSH(VyOSSSH):
"""Implement methods for interacting with EdgeOS EdgeRouter network devices."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -209,11 +181,13 @@
Classes
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def save_config(self, cmd="save", confirm=False, confirm_response=""):
+ def save_config(
+ self, cmd: str = "save", confirm: bool = False, confirm_response: str = ""
+ ) -> str:
"""Saves Config."""
if confirm is True:
raise ValueError("EdgeRouter does not support save_config confirmation.")
- output = self.send_command(command_string=cmd)
+ output = self._send_command_str(command_string=cmd)
if "Done" not in output:
raise ValueError(f"Save failed with following errors:\n\n{output}")
return output
Implements support for Ubiquity EdgeSwitch devices.
@@ -305,131 +282,104 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -442,7 +392,7 @@
Inherited members
This is NOT for EdgeRouter devices.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
self._test_channel_read()
self.set_base_prompt()
self.enable()
@@ -454,23 +404,32 @@
Checks if the device is in configuration mode or not.
Source code
-
def check_config_mode(self, check_string=")#"):
+
def check_config_mode(self, check_string: str = ")#", pattern: str = "") -> bool:
"""Checks if the device is in configuration mode or not."""
- return super().check_config_mode(check_string=check_string)
Implements support for Ubiquity EdgeSwitch devices.
@@ -607,136 +575,109 @@
Inherited members
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class UbiquitiUnifiSwitchSSH(UbiquitiEdgeSSH):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
When SSHing to a UniFi switch, the session initially starts at a Linux
@@ -758,7 +699,7 @@
Inherited members
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -792,7 +733,7 @@
Methods
environment.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
When SSHing to a UniFi switch, the session initially starts at a Linux
@@ -824,7 +765,6 @@
class UbiquitiUnifiSwitchSSH(UbiquitiEdgeSSH):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
When SSHing to a UniFi switch, the session initially starts at a Linux
@@ -49,7 +49,7 @@
Module netmiko.ubiquiti.unifiswitch_ssh
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -75,7 +75,7 @@
Implements support for Ubiquity EdgeSwitch devices.
@@ -85,136 +85,109 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class UbiquitiUnifiSwitchSSH(UbiquitiEdgeSSH):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
When SSHing to a UniFi switch, the session initially starts at a Linux
@@ -236,7 +209,7 @@
Classes
time.sleep(0.3 * self.global_delay_factor)
self.clear_buffer()
- def cleanup(self, command="exit"):
+ def cleanup(self, command: str = "exit") -> None:
"""Gracefully exit the SSH session."""
try:
# The pattern="" forces use of send_command_timing
@@ -270,7 +243,7 @@
Methods
environment.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
When SSHing to a UniFi switch, the session initially starts at a Linux
@@ -302,7 +275,6 @@
from pathlib import Path
import functools
from datetime import datetime
-from netmiko._textfsm import _clitable as clitable
-from netmiko._textfsm._clitable import CliTableError
+from textfsm import clitable
+from textfsm.clitable import CliTableError
from netmiko import log
+# For decorators
+F = TypeVar("F", bound=Callable[..., Any])
+
+
+if TYPE_CHECKING:
+ from netmiko.base_connection import BaseConnection
+ from os import PathLike
+
try:
from ttp import ttp
@@ -53,10 +74,10 @@
Module netmiko.utilities
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
+if sys.version_info[:2] >= (3, 7):
+ import importlib.resources as pkg_resources
+else:
+ import importlib_resources as pkg_resources
try:
import serial.tools.list_ports
@@ -109,7 +130,7 @@
with io.open(yaml_file, "rt", encoding="utf-8") as fname:
return yaml.safe_load(fname)
except IOError:
- sys.exit(f"Unable to open YAML file: {yaml_file}")
+ sys.exit("Unable to open YAML file")
-def load_devices(file_name=None):
+def load_devices(file_name: Union[str, bytes, "PathLike[Any]", None] = None) -> Any:
"""Find and load .netmiko.yml file."""
yaml_devices_file = find_cfg_file(file_name)
return load_yaml_file(yaml_devices_file)
-def find_cfg_file(file_name=None):
+def find_cfg_file(
+ file_name: Union[str, bytes, "PathLike[Any]", None] = None
+) -> Union[str, bytes, "PathLike[Any]"]:
"""
Search for netmiko_tools inventory file in the following order:
NETMIKO_TOOLS_CFG environment variable
@@ -137,9 +160,8 @@
Module netmiko.utilities
Look for file named: .netmiko.yml or netmiko.yml
Also allow NETMIKO_TOOLS_CFG to point directly at a file
"""
- if file_name:
- if os.path.isfile(file_name):
- return file_name
+ if file_name and os.path.isfile(file_name):
+ return file_name
optional_path = os.environ.get("NETMIKO_TOOLS_CFG", "")
if os.path.isfile(optional_path):
return optional_path
@@ -156,7 +178,7 @@
raise ValueError(msg)
-def get_template_dir(_skip_ntc_package=False):
+def get_template_dir(_skip_ntc_package: bool = False) -> str:
"""
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.
+ 3) ~/ntc-templates/ntc_templates/templates.
If `index` file is not found in any of these locations, raise ValueError
@@ -303,19 +327,21 @@
Module netmiko.utilities
else:
# Try 'pip installed' ntc-templates
try:
- with importresources_path(
- package="ntc_templates", resource="templates"
+ with pkg_resources.path(
+ package="ntc_templates", resource="parse.py"
) as posix_path:
# Example: /opt/venv/netmiko/lib/python3.8/site-packages/ntc_templates/templates
- template_dir = str(posix_path)
+ template_dir = str(posix_path.parent.joinpath("templates"))
# This is for Netmiko automated testing
if _skip_ntc_package:
raise ModuleNotFoundError()
except ModuleNotFoundError:
- # Finally check in ~/ntc-templates/templates
+ # Finally check in ~/ntc-templates/ntc_templates/templates
home_dir = os.path.expanduser("~")
- template_dir = os.path.join(home_dir, "ntc-templates", "templates")
+ template_dir = os.path.join(
+ home_dir, "ntc-templates", "ntc_templates", "templates"
+ )
index = os.path.join(template_dir, "index")
if not os.path.isdir(template_dir) or not os.path.isfile(index):
@@ -323,33 +349,47 @@
Module netmiko.utilities
return os.path.abspath(template_dir)
-def clitable_to_dict(cli_table):
+def clitable_to_dict(cli_table: clitable.CliTable) -> List[Dict[str, str]]:
"""Converts TextFSM cli_table object to list of dictionaries."""
- objs = []
+ return_list = []
for row in cli_table:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[cli_table.header[index].lower()] = element
- objs.append(temp_dict)
- return objs
+ return_list.append(temp_dict)
+ return return_list
-def _textfsm_parse(textfsm_obj, raw_output, attrs, template_file=None):
+def _textfsm_parse(
+ textfsm_obj: clitable.CliTable,
+ raw_output: str,
+ attrs: Dict[str, str],
+ template_file: Optional[str] = None,
+) -> Union[str, List[Dict[str, str]]]:
"""Perform the actual TextFSM parsing using the CliTable object."""
+ tfsm_parse: Callable[..., Any] = textfsm_obj.ParseCmd
try:
# Parse output through template
if template_file is not None:
- textfsm_obj.ParseCmd(raw_output, templates=template_file)
+ tfsm_parse(raw_output, templates=template_file)
else:
- textfsm_obj.ParseCmd(raw_output, attrs)
+ tfsm_parse(raw_output, attrs)
+
structured_data = clitable_to_dict(textfsm_obj)
- output = raw_output if structured_data == [] else structured_data
- return output
+ if structured_data == []:
+ return raw_output
+ else:
+ return structured_data
except (FileNotFoundError, CliTableError):
return raw_output
-def get_structured_data(raw_output, platform=None, command=None, template=None):
+def get_structured_data_textfsm(
+ raw_output: str,
+ platform: Optional[str] = None,
+ command: Optional[str] = None,
+ template: Optional[str] = None,
+) -> Union[str, List[Dict[str, str]]]:
"""
Convert raw CLI output to structured data using TextFSM template.
@@ -369,52 +409,64 @@
Module netmiko.utilities
template_dir = get_template_dir()
index_file = os.path.join(template_dir, "index")
textfsm_obj = clitable.CliTable(index_file, template_dir)
- return _textfsm_parse(textfsm_obj, raw_output, attrs)
+ output = _textfsm_parse(textfsm_obj, raw_output, attrs)
+
+ # Retry the output if "cisco_xe" and not structured data
+ if platform and "cisco_xe" in platform:
+ if not isinstance(output, list):
+ attrs["Platform"] = "cisco_ios"
+ output = _textfsm_parse(textfsm_obj, raw_output, attrs)
+ return output
else:
template_path = Path(os.path.expanduser(template))
template_file = template_path.name
- template_dir = template_path.parents[0]
+ template_dir_alt = template_path.parents[0]
# CliTable with no index will fall-back to a TextFSM parsing behavior
- textfsm_obj = clitable.CliTable(template_dir=template_dir)
+ textfsm_obj = clitable.CliTable(template_dir=template_dir_alt)
return _textfsm_parse(
textfsm_obj, raw_output, attrs, template_file=template_file
)
-def get_structured_data_ttp(raw_output, template=None):
+# For compatibility
+get_structured_data = get_structured_data_textfsm
+
+
+def get_structured_data_ttp(raw_output: str, template: str) -> Union[str, List[Any]]:
"""
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"
+ msg = "\nTTP is not installed. Please PIP install ttp:\n\npip 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")
+ ttp_parser = ttp(data=raw_output, template=template)
+ ttp_parser.parse(one=True)
+ result: List[Any] = ttp_parser.result(format="raw")
+ return result
except Exception:
return raw_output
-def run_ttp_template(connection, template, res_kwargs, **kwargs):
+def run_ttp_template(
+ connection: "BaseConnection",
+ template: Union[str, bytes, "PathLike[Any]"],
+ res_kwargs: Dict[str, Any],
+ **kwargs: Any,
+) -> Any:
"""
Helper function to run TTP template parsing.
:param connection: Netmiko connection object
- :type connection: obj
:param template: TTP template
- :type template: str
:param res_kwargs: ``**res_kwargs`` arguments for TTP result method
- :type res_kwargs: dict
:param kwargs: ``**kwargs`` for TTP object instantiation
- :type kwargs: dict
"""
if not TTP_INSTALLED:
msg = "\nTTP is not installed. Please PIP install ttp:\n" "pip install ttp\n"
@@ -450,11 +502,11 @@
+ return cast(F, wrapper_decorator)
+
+
+def calc_old_timeout(
+ max_loops: Optional[int] = None,
+ delay_factor: Optional[float] = None,
+ loop_delay: float = 0.2,
+ old_timeout: int = 100,
+) -> float:
+ """
+ loop_delay is .2 in Netmiko 3.x
+ delay_factor would multiple the loop delay
+ Number of loops was typically 500
+
+ Thus each loop would sleep (loop_delay * delay_factor) seconds
+ That sleep would happen max_loops time
+
+ Formula is (loop_delay * delay_factor) * max_loops
+
+ There was a way Netmiko's self.timeout could override the default settings and essentially be
+ used to adjust max_loops (this was probably rarely used).
+ """
+ if max_loops is None:
+ max_loops = 500
+ if delay_factor is None:
+ delay_factor = 1.0
+ # This is the logic for having self.timeout override max_loops
+ if delay_factor == 1 and max_loops == 500:
+ max_loops = int(old_timeout / loop_delay)
+
+ return max_loops * loop_delay * delay_factor
loop_delay is .2 in Netmiko 3.x
+delay_factor would multiple the loop delay
+Number of loops was typically 500
+
Thus each loop would sleep (loop_delay * delay_factor) seconds
+That sleep would happen max_loops time
+
Formula is (loop_delay * delay_factor) * max_loops
+
There was a way Netmiko's self.timeout could override the default settings and essentially be
+used to adjust max_loops (this was probably rarely used).
+
+Source code
+
def calc_old_timeout(
+ max_loops: Optional[int] = None,
+ delay_factor: Optional[float] = None,
+ loop_delay: float = 0.2,
+ old_timeout: int = 100,
+) -> float:
+ """
+ loop_delay is .2 in Netmiko 3.x
+ delay_factor would multiple the loop delay
+ Number of loops was typically 500
+
+ Thus each loop would sleep (loop_delay * delay_factor) seconds
+ That sleep would happen max_loops time
+
+ Formula is (loop_delay * delay_factor) * max_loops
+
+ There was a way Netmiko's self.timeout could override the default settings and essentially be
+ used to adjust max_loops (this was probably rarely used).
+ """
+ if max_loops is None:
+ max_loops = 500
+ if delay_factor is None:
+ delay_factor = 1.0
+ # This is the logic for having self.timeout override max_loops
+ if delay_factor == 1 and max_loops == 500:
+ max_loops = int(old_timeout / loop_delay)
+
+ return max_loops * loop_delay * delay_factor
+
+
def check_serial_port(name)
@@ -566,7 +740,7 @@
Functions
returns valid COM Port.
Source code
-
def check_serial_port(name):
+
def check_serial_port(name: str) -> str:
"""returns valid COM Port."""
if not PYSERIAL_INSTALLED:
@@ -578,7 +752,9 @@
Converts TextFSM cli_table object to list of dictionaries.
Source code
-
def clitable_to_dict(cli_table):
+
def clitable_to_dict(cli_table: clitable.CliTable) -> List[Dict[str, str]]:
"""Converts TextFSM cli_table object to list of dictionaries."""
- objs = []
+ return_list = []
for row in cli_table:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[cli_table.header[index].lower()] = element
- objs.append(temp_dict)
- return objs
Also allow NETMIKO_TOOLS_CFG to point directly at a file
Source code
-
def find_cfg_file(file_name=None):
+
def find_cfg_file(
+ file_name: Union[str, bytes, "PathLike[Any]", None] = None
+) -> Union[str, bytes, "PathLike[Any]"]:
"""
Search for netmiko_tools inventory file in the following order:
NETMIKO_TOOLS_CFG environment variable
@@ -696,9 +874,8 @@
Functions
Look for file named: .netmiko.yml or netmiko.yml
Also allow NETMIKO_TOOLS_CFG to point directly at a file
"""
- if file_name:
- if os.path.isfile(file_name):
- return file_name
+ if file_name and os.path.isfile(file_name):
+ return file_name
optional_path = os.environ.get("NETMIKO_TOOLS_CFG", "")
if os.path.isfile(optional_path):
return optional_path
@@ -722,7 +899,7 @@
os = None
# platform might be _ssh, _telnet, _serial strip that off
if platform.count("_") > 1:
- base_platform = platform.split("_")[:-1]
- base_platform = "_".join(base_platform)
+ base_list = platform.split("_")[:-1]
+ base_platform = "_".join(base_list)
else:
base_platform = platform
@@ -825,35 +1016,88 @@
Functions
try:
# 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)
+ parsed_output: Dict[str, Any] = device.parse(command, output=raw_output)
return parsed_output
except Exception:
return raw_output
Convert raw CLI output to structured data using TextFSM template.
+
You can use a straight TextFSM file i.e. specify "template". If no template is specified,
+then you must use an CliTable index file.
+
+Source code
+
def get_structured_data_textfsm(
+ raw_output: str,
+ platform: Optional[str] = None,
+ command: Optional[str] = None,
+ template: Optional[str] = None,
+) -> Union[str, List[Dict[str, str]]]:
+ """
+ Convert raw CLI output to structured data using TextFSM template.
+
+ You can use a straight TextFSM file i.e. specify "template". If no template is specified,
+ then you must use an CliTable index file.
+ """
+ if platform is None or command is None:
+ attrs = {}
+ else:
+ attrs = {"Command": command, "Platform": platform}
+
+ if template is None:
+ if attrs == {}:
+ raise ValueError(
+ "Either 'platform/command' or 'template' must be specified."
+ )
+ template_dir = get_template_dir()
+ index_file = os.path.join(template_dir, "index")
+ textfsm_obj = clitable.CliTable(index_file, template_dir)
+ output = _textfsm_parse(textfsm_obj, raw_output, attrs)
+
+ # Retry the output if "cisco_xe" and not structured data
+ if platform and "cisco_xe" in platform:
+ if not isinstance(output, list):
+ attrs["Platform"] = "cisco_ios"
+ output = _textfsm_parse(textfsm_obj, raw_output, attrs)
+ return output
+ else:
+ template_path = Path(os.path.expanduser(template))
+ template_file = template_path.name
+ template_dir_alt = template_path.parents[0]
+ # CliTable with no index will fall-back to a TextFSM parsing behavior
+ textfsm_obj = clitable.CliTable(template_dir=template_dir_alt)
+ return _textfsm_parse(
+ textfsm_obj, raw_output, attrs, template_file=template_file
+ )
def get_structured_data_ttp(raw_output: str, template: str) -> Union[str, List[Any]]:
"""
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"
+ msg = "\nTTP is not installed. Please PIP install ttp:\n\npip 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")
+ ttp_parser = ttp(data=raw_output, template=template)
+ ttp_parser.parse(one=True)
+ result: List[Any] = ttp_parser.result(format="raw")
+ return result
except Exception:
return raw_output
@@ -866,19 +1110,19 @@
Functions
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.
+3) ~/ntc-templates/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(_skip_ntc_package=False):
+
def get_template_dir(_skip_ntc_package: bool = False) -> str:
"""
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.
+ 3) ~/ntc-templates/ntc_templates/templates.
If `index` file is not found in any of these locations, raise ValueError
@@ -908,19 +1152,21 @@
Functions
else:
# Try 'pip installed' ntc-templates
try:
- with importresources_path(
- package="ntc_templates", resource="templates"
+ with pkg_resources.path(
+ package="ntc_templates", resource="parse.py"
) as posix_path:
# Example: /opt/venv/netmiko/lib/python3.8/site-packages/ntc_templates/templates
- template_dir = str(posix_path)
+ template_dir = str(posix_path.parent.joinpath("templates"))
# This is for Netmiko automated testing
if _skip_ntc_package:
raise ModuleNotFoundError()
except ModuleNotFoundError:
- # Finally check in ~/ntc-templates/templates
+ # Finally check in ~/ntc-templates/ntc_templates/templates
home_dir = os.path.expanduser("~")
- template_dir = os.path.join(home_dir, "ntc-templates", "templates")
+ template_dir = os.path.join(
+ home_dir, "ntc-templates", "ntc_templates", "templates"
+ )
index = os.path.join(template_dir, "index")
if not os.path.isdir(template_dir) or not os.path.isfile(index):
@@ -935,7 +1181,7 @@
with io.open(yaml_file, "rt", encoding="utf-8") as fname:
return yaml.safe_load(fname)
except IOError:
- sys.exit(f"Unable to open YAML file: {yaml_file}")
Implement methods for interacting with VyOS network devices.
@@ -53,138 +53,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class VyOSSSH(CiscoSSHConnection):
+
class VyOSSSH(NoEnable, CiscoSSHConnection):
"""Implement methods for interacting with VyOS network devices."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -194,42 +167,43 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -470,20 +448,33 @@
Implement methods for interacting with VyOS network devices.
@@ -149,138 +183,111 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
-
class VyOSSSH(CiscoSSHConnection):
+
class VyOSSSH(NoEnable, CiscoSSHConnection):
"""Implement methods for interacting with VyOS network devices."""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -290,42 +297,43 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read()
self.set_base_prompt()
@@ -566,20 +578,33 @@
import time
+from typing import Any
+
from netmiko.base_connection import BaseConnection
@@ -31,7 +33,7 @@
Module netmiko.watchguard.fireware_ssh
Implements methods for communicating with Watchguard Firebox firewalls.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
@@ -43,19 +45,23 @@
Implements methods for communicating with Watchguard Firebox firewalls.
@@ -79,131 +85,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -212,7 +191,7 @@
Classes
Implements methods for communicating with Watchguard Firebox firewalls.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
@@ -224,19 +203,23 @@
Implements methods for communicating with Watchguard Firebox firewalls.
@@ -53,131 +53,104 @@
Classes
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
@@ -186,7 +159,7 @@
Classes
Implements methods for communicating with Watchguard Firebox firewalls.
"""
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""
Prepare the session after the connection has been established.
@@ -198,19 +171,23 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
from netmiko.base_connection import BaseConnection
-import time
+
import time
+import re
+from typing import Any, Optional
+
+from netmiko.base_connection import BaseConnection
class YamahaBase(BaseConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -35,13 +38,21 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class YamahaBase(BaseConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -255,13 +245,21 @@
def check_config_mode(self, check_string: str = "#", pattern: str = "") -> bool:
"""Checks if the device is in administrator mode or not."""
return super().check_config_mode(check_string=check_string, pattern=pattern)
def exit_enable_mode(self, exit_command: str = "exit") -> str:
"""
When any changes have been made, the prompt 'Save new configuration ? (Y/N)'
appears before exiting. Ignore this by entering 'N'.
@@ -374,7 +366,7 @@
Methods
if "(Y/N)" in output:
self.write_channel("N")
if self.base_prompt not in output:
- output += self.read_until_prompt()
+ output += self.read_until_prompt(read_entire_line=True)
if self.check_enable_mode():
raise ValueError("Failed to exit enable mode.")
return output
def save_config(
+ self, cmd: str = "save", confirm: bool = False, confirm_response: str = ""
+) -> str:
"""Saves Config."""
if confirm is True:
raise ValueError("Yamaha does not support save_config confirmation.")
self.enable()
# Some devices are slow so match on trailing-prompt if you can
- return self.send_command(command_string=cmd)
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -420,8 +414,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ZteZxrosTelnet(ZteZxrosBase):
@staticmethod
- def _process_option(telnet_sock, cmd, opt):
+ def _process_option(telnet_sock: socket, cmd: bytes, opt: bytes) -> None:
"""
ZTE need manually reply DO ECHO to enable echo command.
enable ECHO, SGA, set window size to [500, 50]
@@ -400,8 +346,9 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ZteZxrosBase(CiscoBaseConnection):
- def session_preparation(self):
+ def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -239,13 +218,15 @@
Prepare the session after the connection has been established.
Source code
-
def session_preparation(self):
+
def session_preparation(self) -> None:
"""Prepare the session after the connection has been established."""
self._test_channel_read(pattern=r"[>#]")
self.set_base_prompt()
@@ -316,9 +299,8 @@
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
: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 disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
: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
+ (default: True)
: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
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
Source code
class ZteZxrosTelnet(ZteZxrosBase):
@staticmethod
- def _process_option(telnet_sock, cmd, opt):
+ def _process_option(telnet_sock: socket, cmd: bytes, opt: bytes) -> None:
"""
ZTE need manually reply DO ECHO to enable echo command.
enable ECHO, SGA, set window size to [500, 50]
@@ -711,8 +640,9 @@
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+
Netmiko translates the meaning of "enable" mode to be a proxy for "can
+go into config mode". In other words, that you ultimately have privileges
+to execute configuration changes.
+
The expectation on platforms that have no method for elevating privileges
+is that the standard default privileges allow configuration changes.
+
Consequently check_enable_mode returns True by default for platforms that
+don't explicitly support enable mode.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+
+ :param username: Username to authenticate against target device if
+ required.
+
+ :param password: Password to authenticate against target device if
+ required.
+
+ :param secret: The enable password if target device requires one.
+
+ :param port: The destination port used to connect to the target
+ device.
+
+ :param device_type: Class selection based on device type.
+
+ :param verbose: Enable additional messages to standard output.
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+
+ :param use_keys: Connect to target device using SSH keys.
+
+ :param key_file: Filename path of the SSH key file to use.
+
+ :param pkey: SSH key object to use.
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+
+ :param disabled_algorithms: Dictionary of SSH algorithms to disable. Refer to the Paramiko
+ documentation for a description of the expected format.
+
+ :param allow_agent: Enable use of SSH key-agent.
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+
+ :param timeout: Connection timeout.
+
+ :param session_timeout: Set a timeout for parallel requests.
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+
+ :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).
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+
: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: True)
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+
+ :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).
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+
+ :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.
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+
+ :param delay_factor_compat: Set send_command and send_command_timing back to using Netmiko
+ 3.x behavior for delay_factor/global_delay_factor/max_loops. This argument will be
+ eliminated in Netmiko 5.x (default: False).
+