Implement methods for interacting with Allied Telesis devices.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class AlliedTelesisAwplusBase(CiscoBaseConnection):
+ """Implement methods for interacting with Allied Telesis devices."""
+
+ def session_preparation(self):
+ """
+ Prepare the session after the connection has been established.
+
+ Disable paging (the '--more--' prompts).
+ Set the base prompt for interaction ('>').
+ """
+ """ AWPlus Configuration """
+
+ self.disable_paging()
+ self.set_base_prompt()
+ time.sleep(0.3 * self.global_delay_factor)
+
+ def _enter_shell(self):
+ """Enter the Bourne Shell."""
+ return self.send_command("start shell sh", expect_string=r"[\$#]")
+
+ def _return_cli(self):
+ """Return to the Awplus CLI."""
+ return self.send_command("exit", expect_string=r"[#>]")
+
+ def exit_config_mode(self, exit_config="exit", pattern=""):
+ """Exit configuration mode."""
+ output = ""
+ if self.check_config_mode():
+ output = self.send_command_timing(
+ exit_config, strip_prompt=False, strip_command=False
+ )
+ if "Exit with uncommitted changes?" in output:
+ output += self.send_command_timing(
+ "yes", strip_prompt=False, strip_command=False
+ )
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
def exit_config_mode(self, exit_config="exit", pattern=""):
+ """Exit configuration mode."""
+ output = ""
+ if self.check_config_mode():
+ output = self.send_command_timing(
+ exit_config, strip_prompt=False, strip_command=False
+ )
+ if "Exit with uncommitted changes?" in output:
+ output += self.send_command_timing(
+ "yes", strip_prompt=False, strip_command=False
+ )
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
+
+
+
+def session_preparation(self)
+
+
+
Prepare the session after the connection has been established.
+
Disable paging (the '–more–' prompts).
+Set the base prompt for interaction ('>').
+
+Source code
+
def session_preparation(self):
+ """
+ Prepare the session after the connection has been established.
+
+ Disable paging (the '--more--' prompts).
+ Set the base prompt for interaction ('>').
+ """
+ """ AWPlus Configuration """
+
+ self.disable_paging()
+ self.set_base_prompt()
+ time.sleep(0.3 * self.global_delay_factor)
Implement methods for interacting with Allied Telesis devices.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class AlliedTelesisAwplusSSH(AlliedTelesisAwplusBase):
+ pass
Implement methods for interacting with Allied Telesis devices.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class AlliedTelesisAwplusSSH(AlliedTelesisAwplusBase):
+ pass
"Failed to enter enable mode. Please ensure you pass "
"the 'secret' argument to ConnectHandler."
)
+
+ # Check if in enable mode
if not self.check_enable_mode():
+ # Send "enable" mode command
self.write_channel(self.normalize_cmd(cmd))
try:
- output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
- if pattern not in output:
+ # Read the command echo
+ end_data = ""
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+ end_data = output.split(cmd.strip())[-1]
+
+ # Search for trailing prompt or password pattern
+ if pattern not in output and self.base_prompt not in end_data:
output += self.read_until_prompt_or_pattern(
pattern=pattern, re_flags=re_flags
)
- self.write_channel(self.normalize_cmd(self.secret))
- if enable_pattern:
+ # Send the "secret" in response to password pattern
+ if re.search(pattern, output):
+ self.write_channel(self.normalize_cmd(self.secret))
+ output += self.read_until_prompt()
+
+ # Search for terminating pattern if defined
+ if enable_pattern and not re.search(enable_pattern, output):
output += self.read_until_pattern(pattern=enable_pattern)
else:
- output += self.read_until_prompt()
if not self.check_enable_mode():
raise ValueError(msg)
except NetmikoTimeoutException:
@@ -1828,6 +1847,7 @@
Module netmiko.base_connection
config_mode_command=None,
cmd_verify=True,
enter_config_mode=True,
+ error_pattern="",
):
"""
Send configuration commands down the SSH channel.
@@ -1864,6 +1884,9 @@
Module netmiko.base_connection
: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
"""
delay_factor = self.select_delay_factor(delay_factor)
if config_commands is None:
@@ -1880,21 +1903,35 @@
Module netmiko.base_connection
cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
output += self.config_mode(*cfg_mode_args)
- if self.fast_cli and self._legacy_mode:
+ # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ 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
)
+
elif not cmd_verify:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
time.sleep(delay_factor * 0.05)
- # Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+
+ # 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
+ )
+ 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
+ )
+
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
@@ -1912,6 +1949,11 @@
Module netmiko.base_connection
new_output = self.read_until_pattern(pattern=pattern)
output += new_output
+ if error_pattern:
+ if re.search(error_pattern, output, flags=re.M):
+ msg = f"Invalid input detected at command: {cmd}"
+ raise ConfigInvalidException(msg)
+
if exit_config_mode:
output += self.exit_config_mode()
output = self._sanitize_output(output)
@@ -2064,6 +2106,41 @@
Module netmiko.base_connection
self.session_log.close()
self.session_log = None
+ def run_ttp(self, template, res_kwargs={}, **kwargs):
+ """
+ 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 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.
+ """
+ return run_ttp_template(
+ connection=self, template=template, res_kwargs=res_kwargs, **kwargs
+ )
+
class TelnetConnection(BaseConnection):
pass
@@ -2401,6 +2478,8 @@
Classes
:type auto_connect: bool
"""
self.remote_conn = None
+ # Does the platform support a configuration mode
+ self._config_mode = True
self.TELNET_RETURN = "\r\n"
if default_enter is None:
@@ -3312,7 +3391,9 @@
"Failed to enter enable mode. Please ensure you pass "
"the 'secret' argument to ConnectHandler."
)
+
+ # Check if in enable mode
if not self.check_enable_mode():
+ # Send "enable" mode command
self.write_channel(self.normalize_cmd(cmd))
try:
- output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
- if pattern not in output:
+ # Read the command echo
+ end_data = ""
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+ end_data = output.split(cmd.strip())[-1]
+
+ # Search for trailing prompt or password pattern
+ if pattern not in output and self.base_prompt not in end_data:
output += self.read_until_prompt_or_pattern(
pattern=pattern, re_flags=re_flags
)
- self.write_channel(self.normalize_cmd(self.secret))
- if enable_pattern:
+ # Send the "secret" in response to password pattern
+ if re.search(pattern, output):
+ self.write_channel(self.normalize_cmd(self.secret))
+ output += self.read_until_prompt()
+
+ # Search for terminating pattern if defined
+ if enable_pattern and not re.search(enable_pattern, output):
output += self.read_until_pattern(pattern=enable_pattern)
else:
- output += self.read_until_prompt()
if not self.check_enable_mode():
raise ValueError(msg)
except NetmikoTimeoutException:
@@ -3981,6 +4075,7 @@
Classes
config_mode_command=None,
cmd_verify=True,
enter_config_mode=True,
+ error_pattern="",
):
"""
Send configuration commands down the SSH channel.
@@ -4017,6 +4112,9 @@
Classes
: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
"""
delay_factor = self.select_delay_factor(delay_factor)
if config_commands is None:
@@ -4033,21 +4131,35 @@
Classes
cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
output += self.config_mode(*cfg_mode_args)
- if self.fast_cli and self._legacy_mode:
+ # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ 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
)
+
elif not cmd_verify:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
time.sleep(delay_factor * 0.05)
- # Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+
+ # 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
+ )
+ 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
+ )
+
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
@@ -4065,6 +4177,11 @@
Classes
new_output = self.read_until_pattern(pattern=pattern)
output += new_output
+ if error_pattern:
+ if re.search(error_pattern, output, flags=re.M):
+ msg = f"Invalid input detected at command: {cmd}"
+ raise ConfigInvalidException(msg)
+
if exit_config_mode:
output += self.exit_config_mode()
output = self._sanitize_output(output)
@@ -4215,7 +4332,42 @@
Classes
"""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
+ self.session_log = None
+
+ def run_ttp(self, template, res_kwargs={}, **kwargs):
+ """
+ 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 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.
+ """
+ return run_ttp_template(
+ connection=self, template=template, res_kwargs=res_kwargs, **kwargs
+ )
"Failed to enter enable mode. Please ensure you pass "
"the 'secret' argument to ConnectHandler."
)
+
+ # Check if in enable mode
if not self.check_enable_mode():
+ # Send "enable" mode command
self.write_channel(self.normalize_cmd(cmd))
try:
- output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
- if pattern not in output:
+ # Read the command echo
+ end_data = ""
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+ end_data = output.split(cmd.strip())[-1]
+
+ # Search for trailing prompt or password pattern
+ if pattern not in output and self.base_prompt not in end_data:
output += self.read_until_prompt_or_pattern(
pattern=pattern, re_flags=re_flags
)
- self.write_channel(self.normalize_cmd(self.secret))
- if enable_pattern:
+ # Send the "secret" in response to password pattern
+ if re.search(pattern, output):
+ self.write_channel(self.normalize_cmd(self.secret))
+ output += self.read_until_prompt()
+
+ # Search for terminating pattern if defined
+ if enable_pattern and not re.search(enable_pattern, output):
output += self.read_until_pattern(pattern=enable_pattern)
else:
- output += self.read_until_prompt()
if not self.check_enable_mode():
raise ValueError(msg)
except NetmikoTimeoutException:
@@ -4946,6 +5111,68 @@
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 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 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.
+
+Source code
+
def run_ttp(self, template, res_kwargs={}, **kwargs):
+ """
+ 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 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.
+ """
+ return run_ttp_template(
+ connection=self, template=template, res_kwargs=res_kwargs, **kwargs
+ )
: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
+:type exit_config_mode: bool
+
:param error_pattern: Regular expression pattern to detect config errors in the
+output.
+:type error_pattern: str
Source code
def send_config_set(
@@ -5469,6 +5699,7 @@
Methods
config_mode_command=None,
cmd_verify=True,
enter_config_mode=True,
+ error_pattern="",
):
"""
Send configuration commands down the SSH channel.
@@ -5505,6 +5736,9 @@
Methods
: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
"""
delay_factor = self.select_delay_factor(delay_factor)
if config_commands is None:
@@ -5521,21 +5755,35 @@
Methods
cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
output += self.config_mode(*cfg_mode_args)
- if self.fast_cli and self._legacy_mode:
+ # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ 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
)
+
elif not cmd_verify:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
time.sleep(delay_factor * 0.05)
- # Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+
+ # 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
+ )
+ 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
+ )
+
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
@@ -5553,6 +5801,11 @@
Methods
new_output = self.read_until_pattern(pattern=pattern)
output += new_output
+ if error_pattern:
+ if re.search(error_pattern, output, flags=re.M):
+ msg = f"Invalid input detected at command: {cmd}"
+ raise ConfigInvalidException(msg)
+
if exit_config_mode:
output += self.exit_config_mode()
output = self._sanitize_output(output)
@@ -5644,7 +5897,9 @@
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
+
Implement methods for interacting with CROS network devices.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class CdotCrosSSH(CiscoBaseConnection):
+ """Implement methods for interacting with CROS network devices."""
+
+ def session_preparation(self):
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read()
+ self.set_base_prompt()
+ self._disable_complete_on_space()
+ self.disable_paging(command="screen-length 0")
+ self.set_terminal_width(command="screen-width 511")
+ time.sleep(0.3 * self.global_delay_factor)
+ self.clear_buffer()
+ return
+
+ def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
+ """CROS requires you not exit from configuration mode."""
+ return super().send_config_set(
+ config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ )
+
+ def check_config_mode(self, check_string=")#", pattern=r"[#\$]"):
+ """Checks if device is in configuration mode"""
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
+
+ def config_mode(self, config_command="config", pattern=""):
+ """Enter configuration mode."""
+ return super().config_mode(config_command=config_command, pattern=pattern)
+
+ def commit(self, comment="", delay_factor=1, and_quit=True):
+ """
+ Commit the candidate configuration.
+
+ Commit the entered configuration. Raise an error and return the failure
+ if the commit fails.
+
+ default:
+ command_string = commit
+ comment:
+ command_string = commit comment <comment>
+
+ """
+
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ command_string = "commit"
+ commit_marker = ["Commit complete", "No modifications to commit"]
+
+ if comment:
+ if '"' in comment:
+ raise ValueError("Invalid comment contains double quote")
+ command_string += f' comment "{comment}"'
+
+ output = self.config_mode()
+ output += self.send_command(
+ command_string,
+ strip_prompt=False,
+ strip_command=True,
+ delay_factor=delay_factor,
+ )
+
+ if not (any(x in output for x in commit_marker)):
+ raise ValueError(f"Commit failed with the following errors:\n\n{output}")
+ if and_quit:
+ self.exit_config_mode()
+ return output
+
+ def check_enable_mode(self, *args, **kwargs):
+ """No enable mode on CROS."""
+ return True
+
+ def enable(self, *args, **kwargs):
+ """No enable mode on CROS."""
+ return ""
+
+ def exit_enable_mode(self, *args, **kwargs):
+ """No enable mode on CROS."""
+ return ""
+
+ def _disable_complete_on_space(self):
+ """
+ CROS tries to auto complete commands when you type a "space" character.
+
+ This is a bad idea for automation as what your program is sending no longer matches
+ the command echo from the device. So we disable this behavior.
+ """
+ delay_factor = self.select_delay_factor(delay_factor=0)
+ time.sleep(delay_factor * 0.1)
+ command = "complete-on-space false"
+ self.write_channel(self.normalize_cmd(command))
+ time.sleep(delay_factor * 0.1)
+ output = self.read_channel()
+ return output
Implement methods for interacting with CROS network devices.
+
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class CdotCrosSSH(CiscoBaseConnection):
+ """Implement methods for interacting with CROS network devices."""
+
+ def session_preparation(self):
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read()
+ self.set_base_prompt()
+ self._disable_complete_on_space()
+ self.disable_paging(command="screen-length 0")
+ self.set_terminal_width(command="screen-width 511")
+ time.sleep(0.3 * self.global_delay_factor)
+ self.clear_buffer()
+ return
+
+ def send_config_set(self, config_commands=None, exit_config_mode=False, **kwargs):
+ """CROS requires you not exit from configuration mode."""
+ return super().send_config_set(
+ config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ )
+
+ def check_config_mode(self, check_string=")#", pattern=r"[#\$]"):
+ """Checks if device is in configuration mode"""
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
+
+ def config_mode(self, config_command="config", pattern=""):
+ """Enter configuration mode."""
+ return super().config_mode(config_command=config_command, pattern=pattern)
+
+ def commit(self, comment="", delay_factor=1, and_quit=True):
+ """
+ Commit the candidate configuration.
+
+ Commit the entered configuration. Raise an error and return the failure
+ if the commit fails.
+
+ default:
+ command_string = commit
+ comment:
+ command_string = commit comment <comment>
+
+ """
+
+ delay_factor = self.select_delay_factor(delay_factor)
+
+ command_string = "commit"
+ commit_marker = ["Commit complete", "No modifications to commit"]
+
+ if comment:
+ if '"' in comment:
+ raise ValueError("Invalid comment contains double quote")
+ command_string += f' comment "{comment}"'
+
+ output = self.config_mode()
+ output += self.send_command(
+ command_string,
+ strip_prompt=False,
+ strip_command=True,
+ delay_factor=delay_factor,
+ )
+
+ if not (any(x in output for x in commit_marker)):
+ raise ValueError(f"Commit failed with the following errors:\n\n{output}")
+ if and_quit:
+ self.exit_config_mode()
+ return output
+
+ def check_enable_mode(self, *args, **kwargs):
+ """No enable mode on CROS."""
+ return True
+
+ def enable(self, *args, **kwargs):
+ """No enable mode on CROS."""
+ return ""
+
+ def exit_enable_mode(self, *args, **kwargs):
+ """No enable mode on CROS."""
+ return ""
+
+ def _disable_complete_on_space(self):
+ """
+ CROS tries to auto complete commands when you type a "space" character.
+
+ This is a bad idea for automation as what your program is sending no longer matches
+ the command echo from the device. So we disable this behavior.
+ """
+ delay_factor = self.select_delay_factor(delay_factor=0)
+ time.sleep(delay_factor * 0.1)
+ command = "complete-on-space false"
+ self.write_channel(self.normalize_cmd(command))
+ time.sleep(delay_factor * 0.1)
+ output = self.read_channel()
+ return output
kwargs.setdefault("allow_auto_change", True)
return super().__init__(*args, **kwargs)
- def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
- 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,
- ):
- return super().enable(
- cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
- )
-
def session_preparation(self):
"""Prepare the session after the connection has been established."""
+ # Make sure the ASA is ready
+ command = "show curpriv\n"
+ self.write_channel(command)
+ self.read_until_pattern(pattern=re.escape(command.strip()))
+
+ # The 'enable' call requires the base_prompt to be set.
+ self.set_base_prompt()
if self.secret:
self.enable()
else:
@@ -74,6 +67,20 @@
Module netmiko.cisco.cisco_asa_ssh
self.set_base_prompt()
+ def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
+ 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,
+ ):
+ return super().enable(
+ cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
+ )
+
def send_command_timing(self, *args, **kwargs):
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
@@ -383,23 +390,16 @@
Inherited members
kwargs.setdefault("allow_auto_change", True)
return super().__init__(*args, **kwargs)
- def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
- 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,
- ):
- return super().enable(
- cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
- )
-
def session_preparation(self):
"""Prepare the session after the connection has been established."""
+ # Make sure the ASA is ready
+ command = "show curpriv\n"
+ self.write_channel(command)
+ self.read_until_pattern(pattern=re.escape(command.strip()))
+
+ # The 'enable' call requires the base_prompt to be set.
+ self.set_base_prompt()
if self.secret:
self.enable()
else:
@@ -418,6 +418,20 @@
Inherited members
self.set_base_prompt()
+ def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
+ 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,
+ ):
+ return super().enable(
+ cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
+ )
+
def send_command_timing(self, *args, **kwargs):
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
@@ -681,6 +695,13 @@
Methods
def session_preparation(self):
"""Prepare the session after the connection has been established."""
+ # Make sure the ASA is ready
+ command = "show curpriv\n"
+ self.write_channel(command)
+ self.read_until_pattern(pattern=re.escape(command.strip()))
+
+ # The 'enable' call requires the base_prompt to be set.
+ self.set_base_prompt()
if self.secret:
self.enable()
else:
@@ -753,6 +774,7 @@
output += self.read_until_pattern(
pattern=re.escape(exit_config.strip())
)
+ # Read until we detect either an Uncommitted change or the end prompt
+ if not re.search(r"(Uncommitted|#$)", output):
+ output += self.read_until_pattern(pattern=r"(Uncommitted|#$)")
if "Uncommitted changes found" in output:
self.write_channel(self.normalize_cmd("no\n"))
output += self.read_until_pattern(pattern=r"[>#]")
@@ -508,6 +511,9 @@
Classes
output += self.read_until_pattern(
pattern=re.escape(exit_config.strip())
)
+ # Read until we detect either an Uncommitted change or the end prompt
+ if not re.search(r"(Uncommitted|#$)", output):
+ output += self.read_until_pattern(pattern=r"(Uncommitted|#$)")
if "Uncommitted changes found" in output:
self.write_channel(self.normalize_cmd("no\n"))
output += self.read_until_pattern(pattern=r"[>#]")
@@ -701,6 +707,9 @@
Methods
output += self.read_until_pattern(
pattern=re.escape(exit_config.strip())
)
+ # Read until we detect either an Uncommitted change or the end prompt
+ if not re.search(r"(Uncommitted|#$)", output):
+ output += self.read_until_pattern(pattern=r"(Uncommitted|#$)")
if "Uncommitted changes found" in output:
self.write_channel(self.normalize_cmd("no\n"))
output += self.read_until_pattern(pattern=r"[>#]")
@@ -779,6 +788,7 @@
kwargs.setdefault("allow_auto_change", True)
return super().__init__(*args, **kwargs)
- def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
- 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,
- ):
- return super().enable(
- cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
- )
-
def session_preparation(self):
"""Prepare the session after the connection has been established."""
+ # Make sure the ASA is ready
+ command = "show curpriv\n"
+ self.write_channel(command)
+ self.read_until_pattern(pattern=re.escape(command.strip()))
+
+ # The 'enable' call requires the base_prompt to be set.
+ self.set_base_prompt()
if self.secret:
self.enable()
else:
@@ -330,6 +323,20 @@
Inherited members
self.set_base_prompt()
+ def check_config_mode(self, check_string=")#", pattern=r"[>\#]"):
+ 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,
+ ):
+ return super().enable(
+ cmd=cmd, pattern=pattern, enable_pattern=enable_pattern, re_flags=re_flags
+ )
+
def send_command_timing(self, *args, **kwargs):
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
@@ -593,6 +600,13 @@
Methods
def session_preparation(self):
"""Prepare the session after the connection has been established."""
+ # Make sure the ASA is ready
+ command = "show curpriv\n"
+ self.write_channel(command)
+ self.read_until_pattern(pattern=re.escape(command.strip()))
+
+ # The 'enable' call requires the base_prompt to be set.
+ self.set_base_prompt()
if self.secret:
self.enable()
else:
@@ -665,6 +679,7 @@
"Failed to enter enable mode. Please ensure you pass "
"the 'secret' argument to ConnectHandler."
)
+
+ # Check if in enable mode
if not self.check_enable_mode():
+ # Send "enable" mode command
self.write_channel(self.normalize_cmd(cmd))
try:
- output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
- if pattern not in output:
+ # Read the command echo
+ end_data = ""
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+ end_data = output.split(cmd.strip())[-1]
+
+ # Search for trailing prompt or password pattern
+ if pattern not in output and self.base_prompt not in end_data:
output += self.read_until_prompt_or_pattern(
pattern=pattern, re_flags=re_flags
)
- self.write_channel(self.normalize_cmd(self.secret))
- if enable_pattern:
+ # Send the "secret" in response to password pattern
+ if re.search(pattern, output):
+ self.write_channel(self.normalize_cmd(self.secret))
+ output += self.read_until_prompt()
+
+ # Search for terminating pattern if defined
+ if enable_pattern and not re.search(enable_pattern, output):
output += self.read_until_pattern(pattern=enable_pattern)
else:
- output += self.read_until_prompt()
if not self.check_enable_mode():
raise ValueError(msg)
except NetmikoTimeoutException:
@@ -2499,6 +2534,7 @@
Classes
config_mode_command=None,
cmd_verify=True,
enter_config_mode=True,
+ error_pattern="",
):
"""
Send configuration commands down the SSH channel.
@@ -2535,6 +2571,9 @@
Classes
: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
"""
delay_factor = self.select_delay_factor(delay_factor)
if config_commands is None:
@@ -2551,21 +2590,35 @@
Classes
cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
output += self.config_mode(*cfg_mode_args)
- if self.fast_cli and self._legacy_mode:
+ # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ 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
)
+
elif not cmd_verify:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
time.sleep(delay_factor * 0.05)
- # Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+
+ # 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
+ )
+ 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
+ )
+
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
@@ -2583,6 +2636,11 @@
Classes
new_output = self.read_until_pattern(pattern=pattern)
output += new_output
+ if error_pattern:
+ if re.search(error_pattern, output, flags=re.M):
+ msg = f"Invalid input detected at command: {cmd}"
+ raise ConfigInvalidException(msg)
+
if exit_config_mode:
output += self.exit_config_mode()
output = self._sanitize_output(output)
@@ -2733,7 +2791,42 @@
Classes
"""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
+ self.session_log = None
+
+ def run_ttp(self, template, res_kwargs={}, **kwargs):
+ """
+ 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 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.
+ """
+ return run_ttp_template(
+ connection=self, template=template, res_kwargs=res_kwargs, **kwargs
+ )
"Failed to enter enable mode. Please ensure you pass "
"the 'secret' argument to ConnectHandler."
)
+
+ # Check if in enable mode
if not self.check_enable_mode():
+ # Send "enable" mode command
self.write_channel(self.normalize_cmd(cmd))
try:
- output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
- if pattern not in output:
+ # Read the command echo
+ end_data = ""
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd.strip()))
+ end_data = output.split(cmd.strip())[-1]
+
+ # Search for trailing prompt or password pattern
+ if pattern not in output and self.base_prompt not in end_data:
output += self.read_until_prompt_or_pattern(
pattern=pattern, re_flags=re_flags
)
- self.write_channel(self.normalize_cmd(self.secret))
- if enable_pattern:
+ # Send the "secret" in response to password pattern
+ if re.search(pattern, output):
+ self.write_channel(self.normalize_cmd(self.secret))
+ output += self.read_until_prompt()
+
+ # Search for terminating pattern if defined
+ if enable_pattern and not re.search(enable_pattern, output):
output += self.read_until_pattern(pattern=enable_pattern)
else:
- output += self.read_until_prompt()
if not self.check_enable_mode():
raise ValueError(msg)
except NetmikoTimeoutException:
@@ -3464,6 +3570,68 @@
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 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 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.
+
+Source code
+
def run_ttp(self, template, res_kwargs={}, **kwargs):
+ """
+ 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 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.
+ """
+ return run_ttp_template(
+ connection=self, template=template, res_kwargs=res_kwargs, **kwargs
+ )
: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
+:type exit_config_mode: bool
+
:param error_pattern: Regular expression pattern to detect config errors in the
+output.
+:type error_pattern: str
Source code
def send_config_set(
@@ -3987,6 +4158,7 @@
Methods
config_mode_command=None,
cmd_verify=True,
enter_config_mode=True,
+ error_pattern="",
):
"""
Send configuration commands down the SSH channel.
@@ -4023,6 +4195,9 @@
Methods
: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
"""
delay_factor = self.select_delay_factor(delay_factor)
if config_commands is None:
@@ -4039,21 +4214,35 @@
Methods
cfg_mode_args = (config_mode_command,) if config_mode_command else tuple()
output += self.config_mode(*cfg_mode_args)
- if self.fast_cli and self._legacy_mode:
+ # If error_pattern is perform output gathering line by line and not fast_cli mode.
+ 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
)
+
elif not cmd_verify:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
time.sleep(delay_factor * 0.05)
- # Gather output
- output += self._read_channel_timing(
- delay_factor=delay_factor, max_loops=max_loops
- )
+
+ # 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
+ )
+ 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
+ )
+
else:
for cmd in config_commands:
self.write_channel(self.normalize_cmd(cmd))
@@ -4071,6 +4260,11 @@
Methods
new_output = self.read_until_pattern(pattern=pattern)
output += new_output
+ if error_pattern:
+ if re.search(error_pattern, output, flags=re.M):
+ msg = f"Invalid input detected at command: {cmd}"
+ raise ConfigInvalidException(msg)
+
if exit_config_mode:
output += self.exit_config_mode()
output = self._sanitize_output(output)
@@ -4162,7 +4356,9 @@
if "File Not Found" in remote_out:
raise IOError("Unable to find file on remote system")
+ dest_file_name = remote_file.replace("\\", "/").split("/")[-1]
# Parse dir output for filename. Output format is:
- # "10/16/2019 10:00p 6738 {filename}"
+ # "10/16/2019 10:00p 6738 {dest_file_name}"
- pattern = r"\S+\s+\S+\s+(\d+)\s+{}".format(re.escape(remote_file))
+ pattern = r"\S+\s+\S+\s+(\d+)\s+{}".format(re.escape(dest_file_name))
match = re.search(pattern, remote_out)
if not match:
@@ -231,20 +236,7 @@
Implement methods for interacting with Nokia SR OS devices.
-
Not applicable in Nokia SR OS (disabled):
-- exit_enable_mode()
-
Overriden methods to adapt Nokia SR OS behavior (changed):
-- session_preparation()
-- set_base_prompt()
-- config_mode()
-- exit_config_mode()
-- check_config_mode()
-- save_config()
-- commit()
-- strip_prompt()
-- enable()
-- check_enable_mode()
+
Nokia SR OS SSH driver.
Initialize attributes for establishing connection to target device.
:param ip: IP address of target device. Not required if `host` is
@@ -377,461 +369,258 @@
Inherited members
Source code
-
class NokiaSrosSSH(BaseConnection):
- """
- Implement methods for interacting with Nokia SR OS devices.
-
- Not applicable in Nokia SR OS (disabled):
- - exit_enable_mode()
-
- Overriden methods to adapt Nokia SR OS behavior (changed):
- - session_preparation()
- - set_base_prompt()
- - config_mode()
- - exit_config_mode()
- - check_config_mode()
- - save_config()
- - commit()
- - strip_prompt()
- - enable()
- - check_enable_mode()
- """
-
- def session_preparation(self):
- self._test_channel_read()
- self.set_base_prompt()
- # "@" indicates model-driven CLI (vs Classical CLI)
- if "@" in self.base_prompt:
- self._disable_complete_on_space()
- self.set_terminal_width(
- command="environment console width 512", pattern="environment"
- )
- self.disable_paging(command="environment more false")
- # To perform file operations we need to disable paging in classical-CLI also
- self.disable_paging(command="//environment no more")
- else:
- # Classical CLI has no method to set the terminal width nor to disable command
- # complete on space; consequently, cmd_verify needs disabled.
- self.global_cmd_verify = False
- self.disable_paging(command="environment no more", pattern="environment")
-
- # Clear the read buffer
- time.sleep(0.3 * self.global_delay_factor)
- self.clear_buffer()
-
- def set_base_prompt(self, *args, **kwargs):
- """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
-
- def _disable_complete_on_space(self):
- """
- SR-OS tries to auto complete commands when you type a "space" character.
+
class NokiaSrosSSH(NokiaSros):
+ """Nokia SR OS SSH driver."""
- This is a bad idea for automation as what your program is sending no longer matches
- the command echo from the device, so we disable this behavior.
- """
- delay_factor = self.select_delay_factor(delay_factor=0)
- time.sleep(delay_factor * 0.1)
- command = "environment command-completion space false"
- self.write_channel(self.normalize_cmd(command))
- time.sleep(delay_factor * 0.1)
- return self.read_channel()
-
- def enable(self, cmd="enable", pattern="ssword", re_flags=re.IGNORECASE):
- """Enable SR OS administrative mode"""
- if "@" not in self.base_prompt:
- cmd = "enable-admin"
- return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
-
- def check_enable_mode(self, check_string="in admin mode"):
- """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")
- if "ssword" in output:
- self.write_channel(self.RETURN) # send ENTER to pass the password prompt
- self.read_until_prompt()
- return check_string in output
-
- def exit_enable_mode(self, *args, **kwargs):
- """Nokia SR OS does not have a notion of exiting administrative mode"""
- return ""
-
- def config_mode(self, config_command="edit-config exclusive", pattern=r"\(ex\)\["):
- """Enable config edit-mode for Nokia SR OS"""
- output = ""
- # Only model-driven CLI supports config-mode
- if "@" in self.base_prompt:
- output += super().config_mode(
- config_command=config_command, pattern=pattern
- )
- return output
-
- def exit_config_mode(self, *args, **kwargs):
- """Disable config edit-mode for Nokia SR OS"""
- output = self._exit_all()
- # Model-driven CLI
- if "@" in self.base_prompt and "(ex)[" in output:
- # Asterisk indicates changes were made.
- if "*(ex)[" in output:
- log.warning("Uncommitted changes! Discarding changes!")
- output += self._discard()
- cmd = "quit-config"
- self.write_channel(self.normalize_cmd(cmd))
- if self.global_cmd_verify is not False:
- output += self.read_until_pattern(pattern=re.escape(cmd))
- else:
- output += self.read_until_prompt()
- if self.check_config_mode():
- raise ValueError("Failed to exit configuration mode")
- return output
-
- def check_config_mode(self, check_string=r"(ex)[", pattern=r"@"):
- """Check config mode for Nokia SR OS"""
- if "@" not in self.base_prompt:
- # Classical CLI
- return False
- else:
- # Model-driven CLI look for "exclusive"
- return super().check_config_mode(check_string=check_string, pattern=pattern)
-
- def save_config(self, *args, **kwargs):
- """Persist configuration to cflash for Nokia SR OS"""
- return self.send_command(command_string="/admin save", expect_string=r"#")
-
- def send_config_set(self, config_commands=None, exit_config_mode=None, **kwargs):
- """Model driven CLI requires you not exit from configuration mode."""
- if exit_config_mode is None:
- # Set to False if model-driven CLI
- exit_config_mode = False if "@" in self.base_prompt else True
- return super().send_config_set(
- config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
- )
-
- def commit(self, *args, **kwargs):
- """Activate changes from private candidate for Nokia SR OS"""
- output = self._exit_all()
- if "@" in self.base_prompt and "*(ex)[" in output:
- log.info("Apply uncommitted changes!")
- cmd = "commit"
- self.write_channel(self.normalize_cmd(cmd))
- new_output = ""
- 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_pattern(r"@")
- output += new_output
- return output
-
- def _exit_all(self):
- """Return to the 'root' context."""
- output = ""
- exit_cmd = "exit all"
- self.write_channel(self.normalize_cmd(exit_cmd))
- # 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))
- else:
- output += self.read_until_prompt()
- return output
-
- def _discard(self):
- """Discard changes from private candidate for Nokia SR OS"""
- output = ""
- if "@" in self.base_prompt:
- cmd = "discard"
- self.write_channel(self.normalize_cmd(cmd))
- new_output = ""
- 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()
- output += new_output
- return output
-
- def strip_prompt(self, *args, **kwargs):
- """Strip prompt from the output."""
- output = super().strip_prompt(*args, **kwargs)
- if "@" in self.base_prompt:
- # Remove context prompt too
- strips = r"[\r\n]*\!?\*?(\((ex|gl|pr|ro)\))?\[\S*\][\r\n]*"
- return re.sub(strips, "", output)
- else:
- return output
-
- def cleanup(self, command="logout"):
- """Gracefully exit the SSH session."""
- try:
- # The pattern="" forces use of send_command_timing
- if self.check_config_mode(pattern=""):
- self.exit_config_mode()
- except Exception:
- pass
- # Always try to send final 'logout'.
- self._session_log_fin = True
- self.write_channel(command + self.RETURN)
def check_enable_mode(self, check_string="in admin mode"):
- """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")
- if "ssword" in output:
- self.write_channel(self.RETURN) # send ENTER to pass the password prompt
- self.read_until_prompt()
- return check_string in output
-
-
-
-def cleanup(self, command='logout')
-
-
-
Gracefully exit the SSH session.
-
-Source code
-
def cleanup(self, command="logout"):
- """Gracefully exit the SSH session."""
- try:
- # The pattern="" forces use of send_command_timing
- if self.check_config_mode(pattern=""):
- self.exit_config_mode()
- except Exception:
- pass
- # Always try to send final 'logout'.
- self._session_log_fin = True
- self.write_channel(command + self.RETURN)
-
-
-
-def commit(self, *args, **kwargs)
-
-
-
Activate changes from private candidate for Nokia SR OS
-
-Source code
-
def commit(self, *args, **kwargs):
- """Activate changes from private candidate for Nokia SR OS"""
- output = self._exit_all()
- if "@" in self.base_prompt and "*(ex)[" in output:
- log.info("Apply uncommitted changes!")
- cmd = "commit"
- self.write_channel(self.normalize_cmd(cmd))
- new_output = ""
- 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_pattern(r"@")
- output += new_output
- return output
def enable(self, cmd="enable", pattern="ssword", re_flags=re.IGNORECASE):
- """Enable SR OS administrative mode"""
- if "@" not in self.base_prompt:
- cmd = "enable-admin"
- return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
-
-
-
-def exit_config_mode(self, *args, **kwargs)
-
-
-
Disable config edit-mode for Nokia SR OS
-
-Source code
-
def exit_config_mode(self, *args, **kwargs):
- """Disable config edit-mode for Nokia SR OS"""
- output = self._exit_all()
- # Model-driven CLI
- if "@" in self.base_prompt and "(ex)[" in output:
- # Asterisk indicates changes were made.
- if "*(ex)[" in output:
- log.warning("Uncommitted changes! Discarding changes!")
- output += self._discard()
- cmd = "quit-config"
- self.write_channel(self.normalize_cmd(cmd))
- if self.global_cmd_verify is not False:
- output += self.read_until_pattern(pattern=re.escape(cmd))
- else:
- output += self.read_until_prompt()
- if self.check_config_mode():
- raise ValueError("Failed to exit configuration mode")
- return output
-
-
-
-def exit_enable_mode(self, *args, **kwargs)
-
-
-
Nokia SR OS does not have a notion of exiting administrative mode
-
-Source code
-
def exit_enable_mode(self, *args, **kwargs):
- """Nokia SR OS does not have a notion of exiting administrative mode"""
- return ""
-
-
-
-def save_config(self, *args, **kwargs)
-
-
-
Persist configuration to cflash for Nokia SR OS
-
-Source code
-
def save_config(self, *args, **kwargs):
- """Persist configuration to cflash for Nokia SR OS"""
- return self.send_command(command_string="/admin save", expect_string=r"#")
Model driven CLI requires you not exit from configuration mode.
-
-Source code
-
def send_config_set(self, config_commands=None, exit_config_mode=None, **kwargs):
- """Model driven CLI requires you not exit from configuration mode."""
- if exit_config_mode is None:
- # Set to False if model-driven CLI
- exit_config_mode = False if "@" in self.base_prompt else True
- return super().send_config_set(
- config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
- )
-
-
-
-def set_base_prompt(self, *args, **kwargs)
-
-
-
Remove the > when navigating into the different config level.
-
-Source code
-
def set_base_prompt(self, *args, **kwargs):
- """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
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
Source code
-
def strip_prompt(self, *args, **kwargs):
- """Strip prompt from the output."""
- output = super().strip_prompt(*args, **kwargs)
- if "@" in self.base_prompt:
- # Remove context prompt too
- strips = r"[\r\n]*\!?\*?(\((ex|gl|pr|ro)\))?\[\S*\][\r\n]*"
- return re.sub(strips, "", output)
- else:
- return output
+
class NokiaSrosTelnet(NokiaSros):
+ """Nokia SR OS Telnet driver."""
+
+ pass
Implement methods for interacting with Nokia SR OS devices
+for both SSH and telnet.
+
Not applicable in Nokia SR OS (disabled):
+- exit_enable_mode()
+
Overriden methods to adapt Nokia SR OS behavior (changed):
+- session_preparation()
+- set_base_prompt()
+- config_mode()
+- exit_config_mode()
+- check_config_mode()
+- save_config()
+- commit()
+- strip_prompt()
+- enable()
+- check_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 allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class NokiaSros(BaseConnection):
+ """
+ Implement methods for interacting with Nokia SR OS devices
+ for both SSH and telnet.
+
+ Not applicable in Nokia SR OS (disabled):
+ - exit_enable_mode()
+
+ Overriden methods to adapt Nokia SR OS behavior (changed):
+ - session_preparation()
+ - set_base_prompt()
+ - config_mode()
+ - exit_config_mode()
+ - check_config_mode()
+ - save_config()
+ - commit()
+ - strip_prompt()
+ - enable()
+ - check_enable_mode()
+ """
+
+ def session_preparation(self):
+ self._test_channel_read()
+ self.set_base_prompt()
+ # "@" indicates model-driven CLI (vs Classical CLI)
+ if "@" in self.base_prompt:
+ self._disable_complete_on_space()
+ self.set_terminal_width(
+ command="environment console width 512", pattern="environment"
+ )
+ self.disable_paging(command="environment more false")
+ # To perform file operations we need to disable paging in classical-CLI also
+ self.disable_paging(command="//environment no more")
+ else:
+ # Classical CLI has no method to set the terminal width nor to disable command
+ # complete on space; consequently, cmd_verify needs disabled.
+ self.global_cmd_verify = False
+ self.disable_paging(command="environment no more", pattern="environment")
+
+ # Clear the read buffer
+ time.sleep(0.3 * self.global_delay_factor)
+ self.clear_buffer()
+
+ def set_base_prompt(self, *args, **kwargs):
+ """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
+
+ def _disable_complete_on_space(self):
+ """
+ SR-OS tries to auto complete commands when you type a "space" character.
+
+ This is a bad idea for automation as what your program is sending no longer matches
+ the command echo from the device, so we disable this behavior.
+ """
+ delay_factor = self.select_delay_factor(delay_factor=0)
+ time.sleep(delay_factor * 0.1)
+ command = "environment command-completion space false"
+ self.write_channel(self.normalize_cmd(command))
+ time.sleep(delay_factor * 0.1)
+ return self.read_channel()
+
+ def enable(self, cmd="enable", pattern="ssword", re_flags=re.IGNORECASE):
+ """Enable SR OS administrative mode"""
+ if "@" not in self.base_prompt:
+ cmd = "enable-admin"
+ return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
+
+ def check_enable_mode(self, check_string="in admin mode"):
+ """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")
+ if "ssword" in output:
+ self.write_channel(self.RETURN) # send ENTER to pass the password prompt
+ self.read_until_prompt()
+ return check_string in output
+
+ def exit_enable_mode(self, *args, **kwargs):
+ """Nokia SR OS does not have a notion of exiting administrative mode"""
+ return ""
+
+ def config_mode(self, config_command="edit-config exclusive", pattern=r"\(ex\)\["):
+ """Enable config edit-mode for Nokia SR OS"""
+ output = ""
+ # Only model-driven CLI supports config-mode
+ if "@" in self.base_prompt:
+ output += super().config_mode(
+ config_command=config_command, pattern=pattern
+ )
+ return output
+
+ def exit_config_mode(self, *args, **kwargs):
+ """Disable config edit-mode for Nokia SR OS"""
+ output = self._exit_all()
+ # Model-driven CLI
+ if "@" in self.base_prompt and "(ex)[" in output:
+ # Asterisk indicates changes were made.
+ if "*(ex)[" in output:
+ log.warning("Uncommitted changes! Discarding changes!")
+ output += self._discard()
+ cmd = "quit-config"
+ self.write_channel(self.normalize_cmd(cmd))
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd))
+ else:
+ output += self.read_until_prompt()
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
+
+ def check_config_mode(self, check_string=r"(ex)[", pattern=r"@"):
+ """Check config mode for Nokia SR OS"""
+ if "@" not in self.base_prompt:
+ # Classical CLI
+ return False
+ else:
+ # Model-driven CLI look for "exclusive"
+ return super().check_config_mode(check_string=check_string, pattern=pattern)
+
+ def save_config(self, *args, **kwargs):
+ """Persist configuration to cflash for Nokia SR OS"""
+ return self.send_command(command_string="/admin save", expect_string=r"#")
+
+ def send_config_set(self, config_commands=None, exit_config_mode=None, **kwargs):
+ """Model driven CLI requires you not exit from configuration mode."""
+ if exit_config_mode is None:
+ # Set to False if model-driven CLI
+ exit_config_mode = False if "@" in self.base_prompt else True
+ return super().send_config_set(
+ config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ )
+
+ def commit(self, *args, **kwargs):
+ """Activate changes from private candidate for Nokia SR OS"""
+ output = self._exit_all()
+ if "@" in self.base_prompt and "*(ex)[" in output:
+ log.info("Apply uncommitted changes!")
+ cmd = "commit"
+ self.write_channel(self.normalize_cmd(cmd))
+ new_output = ""
+ 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_pattern(r"@")
+ output += new_output
+ return output
+
+ def _exit_all(self):
+ """Return to the 'root' context."""
+ output = ""
+ exit_cmd = "exit all"
+ self.write_channel(self.normalize_cmd(exit_cmd))
+ # 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))
+ else:
+ output += self.read_until_prompt()
+ return output
+
+ def _discard(self):
+ """Discard changes from private candidate for Nokia SR OS"""
+ output = ""
+ if "@" in self.base_prompt:
+ cmd = "discard"
+ self.write_channel(self.normalize_cmd(cmd))
+ new_output = ""
+ 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()
+ output += new_output
+ return output
+
+ def strip_prompt(self, *args, **kwargs):
+ """Strip prompt from the output."""
+ output = super().strip_prompt(*args, **kwargs)
+ if "@" in self.base_prompt:
+ # Remove context prompt too
+ strips = r"[\r\n]*\!?\*?(\((ex|gl|pr|ro)\))?\[\S*\][\r\n]*"
+ return re.sub(strips, "", output)
+ else:
+ return output
+
+ def cleanup(self, command="logout"):
+ """Gracefully exit the SSH session."""
+ try:
+ # The pattern="" forces use of send_command_timing
+ if self.check_config_mode(pattern=""):
+ self.exit_config_mode()
+ except Exception:
+ pass
+ # Always try to send final 'logout'.
+ self._session_log_fin = True
+ self.write_channel(command + self.RETURN)
def check_enable_mode(self, check_string="in admin mode"):
+ """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")
+ if "ssword" in output:
+ self.write_channel(self.RETURN) # send ENTER to pass the password prompt
+ self.read_until_prompt()
+ return check_string in output
+
+
+
+def cleanup(self, command='logout')
+
+
+
Gracefully exit the SSH session.
+
+Source code
+
def cleanup(self, command="logout"):
+ """Gracefully exit the SSH session."""
+ try:
+ # The pattern="" forces use of send_command_timing
+ if self.check_config_mode(pattern=""):
+ self.exit_config_mode()
+ except Exception:
+ pass
+ # Always try to send final 'logout'.
+ self._session_log_fin = True
+ self.write_channel(command + self.RETURN)
+
+
+
+def commit(self, *args, **kwargs)
+
+
+
Activate changes from private candidate for Nokia SR OS
+
+Source code
+
def commit(self, *args, **kwargs):
+ """Activate changes from private candidate for Nokia SR OS"""
+ output = self._exit_all()
+ if "@" in self.base_prompt and "*(ex)[" in output:
+ log.info("Apply uncommitted changes!")
+ cmd = "commit"
+ self.write_channel(self.normalize_cmd(cmd))
+ new_output = ""
+ 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_pattern(r"@")
+ output += new_output
+ return output
def enable(self, cmd="enable", pattern="ssword", re_flags=re.IGNORECASE):
+ """Enable SR OS administrative mode"""
+ if "@" not in self.base_prompt:
+ cmd = "enable-admin"
+ return super().enable(cmd=cmd, pattern=pattern, re_flags=re_flags)
+
+
+
+def exit_config_mode(self, *args, **kwargs)
+
+
+
Disable config edit-mode for Nokia SR OS
+
+Source code
+
def exit_config_mode(self, *args, **kwargs):
+ """Disable config edit-mode for Nokia SR OS"""
+ output = self._exit_all()
+ # Model-driven CLI
+ if "@" in self.base_prompt and "(ex)[" in output:
+ # Asterisk indicates changes were made.
+ if "*(ex)[" in output:
+ log.warning("Uncommitted changes! Discarding changes!")
+ output += self._discard()
+ cmd = "quit-config"
+ self.write_channel(self.normalize_cmd(cmd))
+ if self.global_cmd_verify is not False:
+ output += self.read_until_pattern(pattern=re.escape(cmd))
+ else:
+ output += self.read_until_prompt()
+ if self.check_config_mode():
+ raise ValueError("Failed to exit configuration mode")
+ return output
+
+
+
+def exit_enable_mode(self, *args, **kwargs)
+
+
+
Nokia SR OS does not have a notion of exiting administrative mode
+
+Source code
+
def exit_enable_mode(self, *args, **kwargs):
+ """Nokia SR OS does not have a notion of exiting administrative mode"""
+ return ""
+
+
+
+def save_config(self, *args, **kwargs)
+
+
+
Persist configuration to cflash for Nokia SR OS
+
+Source code
+
def save_config(self, *args, **kwargs):
+ """Persist configuration to cflash for Nokia SR OS"""
+ return self.send_command(command_string="/admin save", expect_string=r"#")
Model driven CLI requires you not exit from configuration mode.
+
+Source code
+
def send_config_set(self, config_commands=None, exit_config_mode=None, **kwargs):
+ """Model driven CLI requires you not exit from configuration mode."""
+ if exit_config_mode is None:
+ # Set to False if model-driven CLI
+ exit_config_mode = False if "@" in self.base_prompt else True
+ return super().send_config_set(
+ config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
+ )
+
+
+
+def set_base_prompt(self, *args, **kwargs)
+
+
+
Remove the > when navigating into the different config level.
+
+Source code
+
def set_base_prompt(self, *args, **kwargs):
+ """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
+
+
+
+def strip_prompt(self, *args, **kwargs)
+
+
+
Strip prompt from the output.
+
+Source code
+
def strip_prompt(self, *args, **kwargs):
+ """Strip prompt from the output."""
+ output = super().strip_prompt(*args, **kwargs)
+ if "@" in self.base_prompt:
+ # Remove context prompt too
+ strips = r"[\r\n]*\!?\*?(\((ex|gl|pr|ro)\))?\[\S*\][\r\n]*"
+ return re.sub(strips, "", output)
+ else:
+ return output
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class NokiaSrosSSH(NokiaSros):
+ """Nokia SR OS SSH driver."""
+
+ pass
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class NokiaSrosTelnet(NokiaSros):
+ """Nokia SR OS Telnet driver."""
+
+ pass
line = match.group(0)
# Format will be 26 -rw- 6738 Jul 30 2016 19:49:50 -07:00 filename
file_size = line.split()[2]
+ else:
+ raise IOError("Unable to parse 'dir' output in remote_file_size method")
+
if "Error opening" in remote_out or "No such file or directory" in remote_out:
raise IOError("Unable to find file on remote system")
else:
@@ -640,6 +643,9 @@
Classes
line = match.group(0)
# Format will be 26 -rw- 6738 Jul 30 2016 19:49:50 -07:00 filename
file_size = line.split()[2]
+ else:
+ raise IOError("Unable to parse 'dir' output in remote_file_size method")
+
if "Error opening" in remote_out or "No such file or directory" in remote_out:
raise IOError("Unable to find file on remote system")
else:
@@ -791,7 +797,7 @@
line = match.group(0)
# Format will be 26 -rw- 6738 Jul 30 2016 19:49:50 -07:00 filename
file_size = line.split()[2]
+ else:
+ raise IOError("Unable to parse 'dir' output in remote_file_size method")
+
if "Error opening" in remote_out or "No such file or directory" in remote_out:
raise IOError("Unable to find file on remote system")
else:
diff --git a/docs/netmiko/sixwind/index.html b/docs/netmiko/sixwind/index.html
index 87a8b7363..e4fd355a5 100644
--- a/docs/netmiko/sixwind/index.html
+++ b/docs/netmiko/sixwind/index.html
@@ -218,6 +218,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
+
+
+Source code
+
class SmciSwitchSmisSSH(SmciSwitchSmisBase):
+ pass
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class SmciSwitchSmisTelnet(SmciSwitchSmisBase):
+ pass
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class SmciSwitchSmisBase(CiscoBaseConnection):
+ def session_preparation(self):
+ """Prepare the session after the connection has been established."""
+ self._test_channel_read(pattern=r"[>#]")
+ self.set_base_prompt()
+ self.config_mode()
+ self.disable_paging(command="set cli pagination off")
+ self.set_terminal_width(command="terminal width 511")
+ self.exit_config_mode()
+ # Clear the read buffer
+ time.sleep(0.3 * self.global_delay_factor)
+ self.clear_buffer()
+
+ 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, *args, **kwargs):
+ """Supermicro switch does not support enable-mode command"""
+ return ""
+
+ def exit_enable_mode(self, *args, **kwargs):
+ """Supermicro switch does not support enable-mode command"""
+ return ""
+
+ def save_config(
+ self, cmd="write startup-config", confirm=False, confirm_response=""
+ ):
+ """Save config"""
+ return super().save_config(
+ cmd=cmd, confirm=confirm, confirm_response=confirm_response
+ )
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class SmciSwitchSmisSSH(SmciSwitchSmisBase):
+ pass
Initialize attributes for establishing connection to target device.
+
+ :param ip: IP address of target device. Not required if `host` is
+ provided.
+ :type ip: str
+
+ :param host: Hostname of target device. Not required if `ip` is
+ provided.
+ :type host: str
+
+ :param username: Username to authenticate against target device if
+ required.
+ :type username: str
+
+ :param password: Password to authenticate against target device if
+ required.
+ :type password: str
+
+ :param secret: The enable password if target device requires one.
+ :type secret: str
+
+ :param port: The destination port used to connect to the target
+ device.
+ :type port: int or None
+
+ :param device_type: Class selection based on device type.
+ :type device_type: str
+
+ :param verbose: Enable additional messages to standard output.
+ :type verbose: bool
+
+ :param global_delay_factor: Multiplication factor affecting Netmiko delays (default: 1).
+ :type global_delay_factor: int
+
+ :param use_keys: Connect to target device using SSH keys.
+ :type use_keys: bool
+
+ :param key_file: Filename path of the SSH key file to use.
+ :type key_file: str
+
+ :param pkey: SSH key object to use.
+ :type pkey: paramiko.PKey
+
+ :param passphrase: Passphrase to use for encrypted key; password will be used for key
+ decryption if not specified.
+ :type passphrase: str
+
+ :param allow_agent: Enable use of SSH key-agent.
+ :type allow_agent: bool
+
+ :param ssh_strict: Automatically reject unknown SSH host keys (default: False, which
+ means unknown SSH host keys will be accepted).
+ :type ssh_strict: bool
+
+ :param system_host_keys: Load host keys from the users known_hosts file.
+ :type system_host_keys: bool
+ :param alt_host_keys: If `True` host keys will be loaded from the file specified in
+ alt_key_file.
+ :type alt_host_keys: bool
+
+ :param alt_key_file: SSH host key file to use (if alt_host_keys=True).
+ :type alt_key_file: str
+
+ :param ssh_config_file: File name of OpenSSH configuration file.
+ :type ssh_config_file: str
+
+ :param timeout: Connection timeout.
+ :type timeout: float
+
+ :param session_timeout: Set a timeout for parallel requests.
+ :type session_timeout: float
+
+ :param auth_timeout: Set a timeout (in seconds) to wait for an authentication response.
+ :type auth_timeout: float
+
+ :param banner_timeout: Set a timeout to wait for the SSH banner (pass to Paramiko).
+ :type banner_timeout: float
+
+ :param keepalive: Send SSH keepalive packets at a specific interval, in seconds.
+ Currently defaults to 0, for backwards compatibility (it will not attempt
+ to keep the connection alive).
+ :type keepalive: int
+
+ :param default_enter: Character(s) to send to correspond to enter key (default:
+
+
).
+:type default_enter: str
+
:param response_return: Character(s) to use in normalized return data to represent
+ enter key (default:
+
+
)
+:type response_return: str
+
:param fast_cli: Provide a way to optimize for performance. Converts select_delay_factor
+ to select smallest of global and specific. Sets default global_delay_factor to .1
+ (default: False)
+ :type fast_cli: boolean
+
+ :param session_log: File path or BufferedIOBase subclass object to write the session log to.
+ :type session_log: str
+
+ :param session_log_record_writes: The session log generally only records channel reads due
+ to eliminate command duplication due to command echo. You can enable this if you
+ want to record both channel reads and channel writes in the log (default: False).
+ :type session_log_record_writes: boolean
+
+ :param session_log_file_mode: "write" or "append" for session_log file mode
+ (default: "write")
+ :type session_log_file_mode: str
+
+ :param allow_auto_change: Allow automatic configuration changes for terminal settings.
+ (default: False)
+ :type allow_auto_change: bool
+
+ :param encoding: Encoding to be used when writing bytes to the output channel.
+ (default: ascii)
+ :type encoding: str
+
+ :param sock: An open socket or socket-like object (such as a `.Channel`) to use for
+ communication to the target host (default: None).
+ :type sock: socket
+
+ :param global_cmd_verify: Control whether command echo verification is enabled or disabled
+ (default: None). Global attribute takes precedence over function `cmd_verify`
+ argument. Value of `None` indicates to use function `cmd_verify` argument.
+ :type global_cmd_verify: bool|None
+
+ :param auto_connect: Control whether Netmiko automatically establishes the connection as
+ part of the object creation (default: True).
+ :type auto_connect: bool
+
+
+Source code
+
class SmciSwitchSmisTelnet(SmciSwitchSmisBase):
+ pass