API: SSHClient and SSHAuth.¶
- class exec_helpers.SSHClient[source]¶
SSHClient helper.
- __init__(host, port=22, username=None, password=None, *, auth=None, verbose=True, ssh_config=None, ssh_auth_map=None, sock=None, keepalive=1, allow_ssh_agent=True)¶
- Parameters:
host (
str
) – remote hostnameport (
int
) – remote ssh portusername (
str | None
) – remote username.password (
str | None
) – remote passwordauth (SSHAuth | None) – credentials for connection
verbose (bool) – show additional error/warning messages
ssh_config (str | paramiko.SSHConfig | dict[str, dict[str, str | int | bool | list[str]]] | HostsSSHConfigs | None) – SSH configuration for connection. Maybe config path, parsed as dict and paramiko parsed.
ssh_auth_map (dict[str, ssh_auth.SSHAuth] | ssh_auth.SSHAuthMapping | None) – SSH authentication information mapped to host names. Useful for complex SSH Proxy cases.
sock (paramiko.ProxyCommand | paramiko.Channel | socket.socket | None) – socket for connection. Useful for ssh proxies support
keepalive (int | bool) – keepalive period
allow_ssh_agent (bool) – use SSH Agent if available
Note
auth has priority over username/password/private_keys
Note
for proxy connection auth information is collected from SSHConfig if ssh_auth_map record is not available
Changed in version 6.0.0: private_keys, auth and verbose became keyword-only arguments
Changed in version 6.0.0: added optional ssh_config for ssh-proxy & low level connection parameters handling
Changed in version 6.0.0: added optional ssh_auth_map for ssh proxy cases with authentication on each step
Changed in version 6.0.0: added optional sock for manual proxy chain handling
Changed in version 6.0.0: keepalive exposed to constructor
Changed in version 6.0.0: keepalive became int, now used in ssh transport as period of keepalive requests
Changed in version 6.0.0: private_keys is deprecated
Changed in version 7.0.0: private_keys is removed
Changed in version 7.0.0: keepalive_mode is removed
Changed in version 7.4.0: return of keepalive_mode to prevent mix with keepalive period. Default is False
Changed in version 8.0.0: expose SSH Agent usage override
- log_mask_re¶
str | None
regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’
- lock¶
threading.RLock
Connection lock for protection from destructive race-conditions (close/reconnect/…)
- logger¶
logging.Logger
Internal logger.
- hostname¶
str
Connection hostname
- port¶
int
Connection port
- is_alive¶
bool
Paramiko status: ready to use|reconnect required
- sudo_mode¶
bool
Use sudo for all calls, except wrapped in connection.sudo context manager.
- keepalive_mode¶
bool
If False - close connection on exit from context manager.
- keepalive_period¶
int | bool
Keepalive period for connection object.
- use_ssh_agent¶
bool
Use SSH Agent if available.
- close()¶
Close connection
- reconnect()¶
Reconnect SSH session
- __enter__()¶
Open context manager
Changed in version 1.1.0: lock on enter
- __exit__(self, exc_type, exc_val, exc_tb)¶
Close context manager and disconnect
Changed in version 1.0.0: disconnect enforced on close
Changed in version 1.1.0: release lock on exit
Changed in version 1.2.1: disconnect enforced on close only not in keepalive mode
- chroot(path)¶
Context manager for changing chroot rules.
- Parameters:
path (str | pathlib.Path | None) – chroot path or none for working without chroot.
- Returns:
context manager with selected chroot state inside
- Return type:
ContextManager
Note
Enter and exit main context manager is produced as well.
New in version 4.1.0.
- sudo(enforce=None)¶
Context manager getter for sudo operation
- Parameters:
enforce (
bool | None
) – Enforce sudo enabled or disabled. By default: None- Return type:
ContextManager[None]
- keepalive(enforce=1)¶
Context manager getter for keepalive operation.
- Parameters:
enforce (
int | bool
) – Enforce keepalive period.- Returns:
context manager with selected keepalive state inside
- Return type:
ContextManager[None]
Note
Enter and exit ssh context manager is produced as well.
New in version 1.2.1.
- execute(command, verbose=False, timeout=1 * 60 * 60, *, log_mask_re=None, stdin=None, open_stdout=True, log_stdout=True, open_stderr=True, log_stderr=True, get_pty=False, width=80, height=24, **kwargs)¶
Execute command and wait for return code.
- Parameters:
command (
str | Iterable[str]
) – Command for executionverbose (
bool
) – Produce log.info records for command call and outputtimeout (
int | float | None
) – Timeout for command execution.log_mask_re (
str | None
) – regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’stdin (
bytes | str | bytearray | None
) – pass STDIN text to the processopen_stdout (
bool
) – open STDOUT stream for readlog_stdout (
bool
) – log STDOUT during readopen_stderr (
bool
) – open STDERR stream for readlog_stderr (
bool
) – log STDERR during readget_pty (
bool
) – Get PTY for connectionwidth (
int
) – PTY widthheight (
int
) – PTY height
- Return type:
- Raises:
ExecHelperTimeoutError – Timeout exceeded
Changed in version 1.2.0: default timeout 1 hour
- __call__(command, verbose=False, timeout=1 * 60 * 60, *, log_mask_re=None, stdin=None, open_stdout=True, log_stdout=True, open_stderr=True, log_stderr=True, get_pty=False, width=80, height=24, **kwargs)¶
Execute command and wait for return code.
- Parameters:
command (
str | Iterable[str]
) – Command for executionverbose (
bool
) – Produce log.info records for command call and outputtimeout (
int | float | None
) – Timeout for command execution.log_mask_re (
str | None
) – regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’stdin (
bytes | str | bytearray | None
) – pass STDIN text to the processopen_stdout (
bool
) – open STDOUT stream for readlog_stdout (
bool
) – log STDOUT during readopen_stderr (
bool
) – open STDERR stream for readlog_stderr (
bool
) – log STDERR during readget_pty (
bool
) – Get PTY for connectionwidth (
int
) – PTY widthheight (
int
) – PTY height
- Return type:
- Raises:
ExecHelperTimeoutError – Timeout exceeded
New in version 3.3.0.
- check_call(command, verbose=False, timeout=1 * 60 * 60, error_info=None, expected=(0,), raise_on_err=True, *, log_mask_re=None, stdin=None, open_stdout=True, log_stdout=True, open_stderr=True, log_stderr=True, get_pty=False, width=80, height=24, exception_class=CalledProcessError, **kwargs)¶
Execute command and check for return code.
- Parameters:
command (
str | Iterable[str]
) – Command for executionverbose (
bool
) – Produce log.info records for command call and outputtimeout (
int | float | None
) – Timeout for command execution.error_info (
str | None
) – Text for error details, if fail happensexpected (Iterable[int | ExitCodes]) – expected return codes (0 by default)
raise_on_err (
bool
) – Raise exception on unexpected return codelog_mask_re (
str | None
) – regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’stdin (
bytes | str | bytearray | None
) – pass STDIN text to the processopen_stdout (
bool
) – open STDOUT stream for readlog_stdout (
bool
) – log STDOUT during readopen_stderr (
bool
) – open STDERR stream for readlog_stderr (
bool
) – log STDERR during readget_pty (
bool
) – Get PTY for connectionwidth (
int
) – PTY widthheight (
int
) – PTY heightexception_class (Type[CalledProcessError]) – Exception class for errors. Subclass of CalledProcessError is mandatory.
- Return type:
- Raises:
ExecHelperTimeoutError – Timeout exceeded
CalledProcessError – Unexpected exit code
Changed in version 1.2.0: default timeout 1 hour
Changed in version 3.2.0: Exception class can be substituted
Changed in version 3.4.0: Expected is not optional, defaults os dependent
- check_stderr(command, verbose=False, timeout=1 * 60 * 60, error_info=None, raise_on_err=True, *, expected=(0,), log_mask_re=None, stdin=None, open_stdout=True, log_stdout=True, open_stderr=True, log_stderr=True, get_pty=False, width=80, height=24, exception_class=CalledProcessError, **kwargs)¶
Execute command expecting return code 0 and empty STDERR.
- Parameters:
command (
str | Iterable[str]
) – Command for executionverbose (
bool
) – Produce log.info records for command call and outputtimeout (
int | float | None
) – Timeout for command execution.error_info (
str | None
) – Text for error details, if fail happensraise_on_err (
bool
) – Raise exception on unexpected return codeexpected (Iterable[int | ExitCodes]) – expected return codes (0 by default)
log_mask_re (
str | None
) – regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’stdin (
bytes | str | bytearray | None
) – pass STDIN text to the processopen_stdout (
bool
) – open STDOUT stream for readlog_stdout (
bool
) – log STDOUT during readopen_stderr (
bool
) – open STDERR stream for readlog_stderr (
bool
) – log STDERR during readget_pty (
bool
) – Get PTY for connectionwidth (
int
) – PTY widthheight (
int
) – PTY heightexception_class (Type[CalledProcessError]) – Exception class for errors. Subclass of CalledProcessError is mandatory.
- Return type:
- Raises:
ExecHelperTimeoutError – Timeout exceeded
CalledProcessError – Unexpected exit code or stderr presents
Changed in version 1.2.0: default timeout 1 hour
Changed in version 3.2.0: Exception class can be substituted
- proxy_to(host, port=None, username=None, password=None, *, auth=None, verbose=True, ssh_config=None, ssh_auth_map=None, keepalive=1)¶
Start new SSH connection using current as proxy.
- Parameters:
host (
str
) – remote hostnameport (
int | None
) – remote ssh portusername (
str | None
) – remote username.password (
str | None
) – remote passwordauth (ssh_auth.SSHAuth | None) – credentials for connection
verbose (
bool
) – show additional error/warning messagesssh_config (str | paramiko.SSHConfig | dict[str, dict[str, str | int | bool | list[str]]] | HostsSSHConfigs | None) – SSH configuration for connection. Maybe config path, parsed as dict and paramiko parsed.
ssh_auth_map (dict[str, SSHAuth] | SSHAuthMapping | None) – SSH authentication information mapped to host names. Useful for complex SSH Proxy cases.
keepalive (
int | bool
) – keepalive period
- Returns:
new ssh client instance using current as a proxy
- Return type:
SSHClientBase
Note
auth has priority over username/password
New in version 6.0.0.
- execute_through_host(hostname, command, *, auth=None, port=22, verbose=False, timeout=1 * 60 * 60, stdin=None, open_stdout=True, log_stdout=True, open_stderr=True, log_stderr=True, log_mask_re='', get_pty=False, width=80, height=24, **kwargs)¶
Execute command on remote host through currently connected host.
- Parameters:
hostname (
str
) – target hostnamecommand (
str | Iterable[str]
) – Command for executionauth (SSHAuth | None) – credentials for target machine
port (
int
) – target portverbose (
bool
) – Produce log.info records for command call and outputtimeout (
int | float | None
) – Timeout for command execution.stdin (
bytes | str | bytearray | None
) – pass STDIN text to the processopen_stdout (
bool
) – open STDOUT stream for readlog_stdout (
bool
) – log STDOUT during readopen_stderr (
bool
) – open STDERR stream for readlog_stderr (
bool
) – log STDERR during readlog_mask_re (
str | None
) – regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’get_pty (
bool
) – open PTY on target machinewidth (
int
) – PTY widthheight (
int
) – PTY height
- Return type:
- Raises:
ExecHelperTimeoutError – Timeout exceeded
Changed in version 1.2.0: default timeout 1 hour
Changed in version 3.2.0: Expose pty options as optional keyword-only arguments
Changed in version 3.2.0: Exception class can be substituted
Changed in version 4.0.0: Expose stdin and log_mask_re as optional keyword-only arguments
Changed in version 6.0.0: Move channel open to separate method and make proper ssh-proxy usage
Changed in version 6.0.0: only hostname and command are positional argument, target_port changed to port.
- classmethod execute_together(remotes, command, timeout=1 * 60 * 60, expected=(0,), raise_on_err=True, *, stdin=None, open_stdout=True, open_stderr=True, log_mask_re='', exception_class=ParallelCallProcessError, **kwargs)¶
Execute command on multiple remotes in async mode.
- Parameters:
remotes (Iterable[SSHClient]) – Connections to execute on
command (
str | Iterable[str]
) – Command for executiontimeout (
int | float | None
) – Timeout for command execution.expected (Iterable[int | ExitCodes]) – expected return codes (0 by default)
raise_on_err (
bool
) – Raise exception on unexpected return codestdin (
bytes | str | bytearray | None
) – pass STDIN text to the processopen_stdout (
bool
) – open STDOUT stream for readopen_stderr (
bool
) – open STDERR stream for readlog_mask_re (
str | None
) – regex lookup rule to mask command for logger. all MATCHED groups will be replaced by ‘<masked>’exception_class (Type[ParallelCallProcessError]) – Exception to raise on error. Mandatory subclass of ParallelCallProcessError
- Returns:
dictionary {(hostname, port): result}
- Return type:
dict[tuple[str, int], ExecResult]
- Raises:
ParallelCallProcessError – Unexpected any code at lest on one target
ParallelCallExceptionsError – At lest one exception raised during execution (including timeout)
Changed in version 1.2.0: default timeout 1 hour
Changed in version 3.2.0: Exception class can be substituted
Changed in version 3.4.0: Expected is not optional, defaults os dependent
Changed in version 4.0.0: Expose stdin and log_mask_re as optional keyword-only arguments
- open(path, mode='r')¶
Open file on remote using SFTP session.
- Parameters:
path (
str
) – filesystem object pathmode (
str
) – open file mode (‘t’ is not supported)
- Returns:
file.open() stream
- Return type:
paramiko.SFTPFile
- exists(path)¶
Check for file existence using SFTP session.
- Parameters:
path (
str
) – filesystem object path- Returns:
path is valid (object exists)
- Return type:
bool
- stat(path)¶
Get stat info for path with following symlinks.
- Parameters:
path (
str
) – filesystem object path- Returns:
stat like information for remote path
- Return type:
paramiko.sftp_attr.SFTPAttributes
- utime(path, times=None):
Set atime, mtime.
- Parameters:
path (
str
) – filesystem object pathtimes (
tuple[int, int] | None
) – (atime, mtime)
- Return type:
None
New in version 1.0.0.
- isfile(path)¶
Check, that path is file using SFTP session.
- Parameters:
path (
str
) – remote path to validate- Returns:
path is file
- Return type:
bool
- isdir(path)¶
Check, that path is directory using SFTP session.
- Parameters:
path (
str
) – remote path to validate- Returns:
path is directory
- Return type:
bool
- islink(path)¶
Check, that path is symlink using SFTP session.
- Parameters:
path (
str
) – remote path to validate- Returns:
path is symlink
- Return type:
bool
- symlink(source, dest)¶
Produce symbolic link like os.symlink.
- Parameters:
source (
str
) – source pathdest (
str
) – source path
- chmod(path, mode)¶
Change the mode (permissions) of a file like os.chmod.
- Parameters:
path (
str
) – filesystem object pathmode (
int
) – new permissions
Non standard methods:
- class exec_helpers.SSHAuth[source]¶
SSH credentials object.
Used to authorize SSHClient. Single SSHAuth object is associated with single host:port. Password and key is private, other data is read-only.
- __init__(username=None, password=None, key=None, keys=None)[source]¶
- Parameters:
username (
str | None
) – remote username.password (
str | None
) – remote passwordkey (
paramiko.PKey | None
) – Main connection keykeys (
Sequence[paramiko.PKey] | None
) – Alternate connection keyskey_filename (
Iterable[str] | str | None
) – filename(s) for additional key filespassphrase (
str | None
) – passphrase for keys. Need, if differs from password
Changed in version 1.0.0: added: key_filename, passphrase arguments
- username¶
str | None
- public_key¶
str | None
public key for stored private key if presents else None
- key_filename¶
Collection[str]
Key filename(s).New in version 1.0.0.
- enter_password(self, tgt)[source]¶
Enter password to STDIN.
Note: required for ‘sudo’ call
- Parameters:
tgt (file) – Target
- connect(client, hostname, port=22, log=True, *, sock=None)[source]¶
Connect SSH client object using credentials.
- Parameters:
client (
paramiko.SSHClient
) – SSH Client (low level)hostname (
str
) – remote hostnameport (
int
) – remote ssh portlog (
bool
) – Log on generic connection failuresock (
paramiko.ProxyCommand | paramiko.Channel | socket.socket | None
) – socket for connection. Useful for ssh proxies support
- Raises:
PasswordRequiredException – No password has been set, but required.
AuthenticationException – Authentication failed.
- class exec_helpers.SshExecuteAsyncResult¶
Typed NamedTuple
- interface¶
paramiko.Channel
- stdin¶
paramiko.ChannelFile
- stderr¶
paramiko.ChannelFile | None
- stdout¶
paramiko.ChannelFile | None
- started¶
datetime.datetime
New in version 3.4.1.
- class exec_helpers.HostsSSHConfigs(dict[str, SSHConfig])[source]¶
Specific dictionary for managing SSHConfig records.
Instead of creating new record by request just generate default value and return if not exists.
- class exec_helpers.SSHConfig[source]¶
Parsed SSH Config for creation connection.
- __init__(hostname, port=None, user=None, identityfile=None, proxycommand=None, proxyjump=None, *, controlpath=None, controlmaster=None)[source]¶
SSH Config for creation connection.
- Parameters:
hostname (
str
) – hostname, which config relatesport (
str | int | None
) – remote portuser (
str | None
) – remote useridentityfile (
Collection[str] | None
) – connection ssh keys file namesproxycommand (
str | None
) – proxy command for ssh connectionproxyjump (
str | None
) – proxy host namecontrolpath (
str | None
) – shared socket file path for re-using connection by multiple instancescontrolmaster (
str | bool | None
) – re-use connection
- Raises:
ValueError – Invalid argument provided.
New in version 6.0.0.
- from_ssh_config(ssh_config):
Construct config from Paramiko parsed file.
- Parameters:
ssh_config – paramiko parsed ssh config or it reconstruction as a dict,
- Returns:
SSHConfig with supported values from config
- as_dict¶
dict[str, str | int | bool | list[str]]
Dictionary for rebuilding config.
- hostname¶
str
Hostname which config relates.
- port¶
int | None
Remote port.
- user¶
str | None
Remote user.
- identityfile¶
Collection[str]
Connection ssh keys file names.
- proxycommand¶
str | None
Proxy command for ssh connection.
- proxyjump¶
str | None
Proxy host name.
- controlpath¶
str | None
Shared socket file path for re-using connection by multiple instances.
- controlmaster¶
bool | None
Re-use connection.