Package paramiko :: Module client :: Class SSHClient
[frames] | no frames]

Class SSHClient

source code

object --+
         |
        SSHClient

A high-level representation of a session with an SSH server. This class wraps `.Transport`, `.Channel`, and `.SFTPClient` to take care of most aspects of authenticating and opening channels. A typical use case is:

   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).

.. versionadded:: 1.6

Instance Methods
 
__init__(self)
Create a new SSHClient.
source code
 
load_system_host_keys(self, filename=None)
Load host keys from a system (read-only) file.
source code
 
load_host_keys(self, filename)
Load host keys from a local host-key file.
source code
 
save_host_keys(self, filename)
Save the host keys back to a file.
source code
 
get_host_keys(self)
Get the local `.HostKeys` object.
source code
 
set_log_channel(self, name)
Set the channel for logging.
source code
 
set_missing_host_key_policy(self, policy)
Set the policy to use when connecting to a server that doesn't have a host key in either the system or local `.HostKeys` objects.
source code
 
connect(self, 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)
Connect to an SSH server and authenticate to it.
source code
 
close(self)
Close this SSHClient and its underlying `.Transport`.
source code
 
exec_command(self, command, bufsize=-1, timeout=None, get_pty=False)
Execute a command on the SSH server.
source code
 
invoke_shell(self, term='vt100', width=80, height=24, width_pixels=0, height_pixels=0)
Start an interactive shell session on the SSH server.
source code
 
open_sftp(self)
Open an SFTP session on the SSH server.
source code
 
get_transport(self)
Return the underlying `.Transport` object for this SSH connection.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Properties

Inherited from object: __class__

Method Details

__init__(self)
(Constructor)

source code 

Create a new SSHClient.

Overrides: object.__init__

load_system_host_keys(self, filename=None)

source code 

Load host keys from a system (read-only) file.  Host keys read with
this method will not be saved back by `save_host_keys`.

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).

If ``filename`` is 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.

:param str filename: the filename to read, or ``None``

:raises IOError:
    if a filename was provided and the file could not be read

load_host_keys(self, filename)

source code 

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 `.AutoAddPolicy` adds 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.

:param str filename: the filename to read

:raises IOError: if the filename could not be read

save_host_keys(self, filename)

source code 

Save the host keys back to a file. Only the host keys loaded with `load_host_keys` (plus any added directly) will be saved -- not any host keys loaded with `load_system_host_keys`.

:param str filename: the filename to save to

:raises IOError: if the file could not be written

get_host_keys(self)

source code 

Get the local `.HostKeys` object. This can be used to examine the local host keys or change them.

:return: the local host keys as a `.HostKeys` object.

set_log_channel(self, name)

source code 

Set the channel for logging. The default is ``"paramiko.transport"`` but it can be set to anything you want.

:param str name: new channel name for logging

set_missing_host_key_policy(self, policy)

source code 

Set the policy to use when connecting to a server that doesn't have a
host key in either the system or local `.HostKeys` objects.  The
default policy is to reject all unknown servers (using `.RejectPolicy`).
You may substitute `.AutoAddPolicy` or write your own policy class.

:param .MissingHostKeyPolicy policy:
    the policy to use when receiving a host key from a
    previously-unknown server

connect(self, 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)

source code 

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 `.SSHException`.

Authentication is attempted in the following order of priority:

    - The ``pkey`` or ``key_filename`` passed in (if any)
    - Any key we can find through an SSH agent
    - Any "id_rsa" or "id_dsa" key discoverable in ``~/.ssh/``
    - 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.

:param str hostname: the server to connect to
:param int port: the server port to connect to
:param str username:
    the username to authenticate as (defaults to the current local
    username)
:param str password:
    a password to use for authentication or for unlocking a private key
:param .PKey pkey: an optional private key to use for authentication
:param str key_filename:
    the filename, or list of filenames, of optional private key(s) to
    try for authentication
:param float timeout: an optional timeout (in seconds) for the TCP connect
:param bool allow_agent: set to False to disable connecting to the SSH agent
:param bool look_for_keys:
    set to False to disable searching for discoverable private key
    files in ``~/.ssh/``
:param bool compress: set to True to turn on compression
:param socket sock:
    an open socket or socket-like object (such as a `.Channel`) to use
    for communication to the target host

:raises BadHostKeyException: if the server's host key could not be
    verified
:raises AuthenticationException: if authentication failed
:raises SSHException: if there was any other error connecting or
    establishing an SSH session
:raises socket.error: if a socket error occurred while connecting

exec_command(self, command, bufsize=-1, timeout=None, get_pty=False)

source code 

Execute a command on the SSH server.  A new `.Channel` is 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.

:param str command: the command to execute
:param int bufsize:
    interpreted the same way as by the built-in ``file()`` function in
    Python
:param int timeout:
    set command's channel timeout. See `Channel.settimeout`.settimeout
:return:
    the stdin, stdout, and stderr of the executing command, as a
    3-tuple

:raises SSHException: if the server fails to execute the command

invoke_shell(self, term='vt100', width=80, height=24, width_pixels=0, height_pixels=0)

source code 

Start an interactive shell session on the SSH server.  A new `.Channel`
is opened and connected to a pseudo-terminal using the requested
terminal type and size.

:param str term:
    the terminal type to emulate (for example, ``"vt100"``)
:param int width: the width (in characters) of the terminal window
:param int height: the height (in characters) of the terminal window
:param int width_pixels: the width (in pixels) of the terminal window
:param int height_pixels: the height (in pixels) of the terminal window
:return: a new `.Channel` connected to the remote shell

:raises SSHException: if the server fails to invoke a shell

open_sftp(self)

source code 

Open an SFTP session on the SSH server.

:return: a new `.SFTPClient` session object

get_transport(self)

source code 

Return the underlying `.Transport` object for this SSH connection. This can be used to perform lower-level tasks, like opening specific kinds of channels.

:return: the `.Transport` for this connection