SSH client & key policies
Interface for defining the policy that
SSHClientshould use when the SSH server’s hostname is not in either the system host keys or the application’s keys. Pre-made classes implement policies for automatically adding the key to the application’s
AutoAddPolicy), and for automatically rejecting the key (
This function may be used to ask the user to verify the key, for example.
list of weak references to the object (if defined)
Policy for automatically rejecting the unknown hostname & key. This is used by
A high-level representation of a session with an SSH server. This class wraps
SFTPClientto take care of most aspects of authenticating and opening channels. A typical use case is:
client = SSHClient() client.load_system_host_keys() client.connect('ssh.example.com') stdin, stdout, stderr = client.exec_command('ls -l')
You may pass in explicit overrides for authentication and server host key checking. The default mechanism is to try to use local key files or an SSH agent (if one is running).
Instances of this class may be used as context managers.
New in version 1.6.
Create a new SSHClient.
Close this SSHClient and its underlying
Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It’s good practice to
closeyour client objects anytime you’re done using them, instead of relying on garbage collection.
connect(hostname, port=22, username=None, password=None, pkey=None, key_filename=None, timeout=None, allow_agent=True, look_for_keys=True, compress=False, sock=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, gss_host=None, banner_timeout=None)¶
Connect to an SSH server and authenticate to it. The server’s host key is checked against the system host keys (see
load_system_host_keys) and any local host keys (
load_host_keys). If the server’s hostname is not found in either set of host keys, the missing host key policy is used (see
set_missing_host_key_policy). The default policy is to reject the key and raise an
Authentication is attempted in the following order of priority:
key_filenamepassed in (if any)
- Any key we can find through an SSH agent
- Any “id_rsa”, “id_dsa” or “id_ecdsa” key discoverable in
- Plain username/password auth, if a password was given
If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key.
- hostname (str) – the server to connect to
- port (int) – the server port to connect to
- username (str) – the username to authenticate as (defaults to the current local username)
- password (str) – a password to use for authentication or for unlocking a private key
- pkey (PKey) – an optional private key to use for authentication
- key_filename (str) – the filename, or list of filenames, of optional private key(s) to try for authentication
- timeout (float) – an optional timeout (in seconds) for the TCP connect
- allow_agent (bool) – set to False to disable connecting to the SSH agent
- look_for_keys (bool) – set to False to disable searching for discoverable private key
- compress (bool) – set to True to turn on compression
- sock (socket) – an open socket or socket-like object (such as a
Channel) to use for communication to the target host
- gss_auth (bool) –
Trueif you want to use GSS-API authentication
- gss_kex (bool) – Perform GSS-API Key Exchange and user authentication
- gss_deleg_creds (bool) – Delegate GSS-API client credentials or not
- gss_host (str) – The targets name in the kerberos database. default: hostname
- banner_timeout (float) – an optional timeout (in seconds) to wait for the SSH banner to be presented.
- BadHostKeyException – if the server’s host key could not be verified
- AuthenticationException – if authentication failed
- SSHException – if there was any other error connecting or establishing an SSH session
- socket.error – if a socket error occurred while connecting
Changed in version 1.15: Added the
exec_command(command, bufsize=-1, timeout=None, get_pty=False, environment=None)¶
Execute a command on the SSH server. A new
Channelis opened and the requested command is executed. The command’s input and output streams are returned as Python
file-like objects representing stdin, stdout, and stderr.
- command (str) – the command to execute
- bufsize (int) – interpreted the same way as by the built-in
file()function in Python
- timeout (int) – set command’s channel timeout. See
- environment (dict) –
a dict of shell environment variables, to be merged into the default environment that the remote command executes within.
Servers may silently reject some environment variables; see the warning in
the stdin, stdout, and stderr of the executing command, as a 3-tuple
SSHException – if the server fails to execute the command
Get the local
HostKeysobject. This can be used to examine the local host keys or change them.
Returns: the local host keys as a
Return the underlying
Transportobject for this SSH connection. This can be used to perform lower-level tasks, like opening specific kinds of channels.
Transportfor this connection
invoke_shell(term='vt100', width=80, height=24, width_pixels=0, height_pixels=0, environment=None)¶
Start an interactive shell session on the SSH server. A new
Channelis opened and connected to a pseudo-terminal using the requested terminal type and size.
- term (str) – the terminal type to emulate (for example,
- width (int) – the width (in characters) of the terminal window
- height (int) – the height (in characters) of the terminal window
- width_pixels (int) – the width (in pixels) of the terminal window
- height_pixels (int) – the height (in pixels) of the terminal window
- environment (dict) – the command’s environment
Channelconnected to the remote shell
SSHException – if the server fails to invoke a shell
- term (str) – the terminal type to emulate (for example,
Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via
load_system_host_keys, but will be saved back by
save_host_keys(so they can be modified). The missing host key policy
AutoAddPolicyadds keys to this set and saves them, when connecting to a previously-unknown server.
This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used.
Parameters: filename (str) – the filename to read Raises: IOError – if the filename could not be read
Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by
This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts).
filenameis left as
None, an attempt will be made to read keys from the user’s local “known hosts” file, as used by OpenSSH, and no exception will be raised if the file can’t be read. This is probably only useful on posix.
Parameters: filename (str) – the filename to read, or
Raises: IOError – if a filename was provided and the file could not be read
Parameters: filename (str) – the filename to save to Raises: IOError – if the file could not be written
Set the channel for logging. The default is
"paramiko.transport"but it can be set to anything you want.
Parameters: name (str) – new channel name for logging
Set policy to use when connecting to servers without a known host key.
This method takes class instances, not classes themselves. Thus it must be called as e.g.
Parameters: policy (MissingHostKeyPolicy) – the policy to use when receiving a host key from a previously-unknown server