An SSH Transport attaches to a stream (usually a socket), negotiates anencrypted session, authenticates, and then creates stream tunnels, calledchannels, across the session. Multiple channels can bemultiplexed across a single session (and often are, in the case of portforwardings).
Instances of this class may be used as context managers.
__init__
(sock, default_window_size=2097152, default_max_packet_size=32768, gss_kex=False, gss_deleg_creds=True)¶Create a new SSH session over an existing socket, or socket-likeobject. This only creates the Transport object; it doesn’t beginthe SSH session yet. Use connect or start_client to begin a clientsession, or start_server to begin a server session.
If the object is not actually a socket, it must have the followingmethods:
send(str)
: Writes from 1 tolen(str)
bytes, and returns anint representing the number of bytes written. Returns0 or raisesEOFError
if the stream has been closed.recv(int)
: Reads from 1 toint
bytes and returns them as astring. Returns 0 or raisesEOFError
if the stream has beenclosed.close()
: Closes the socket.settimeout(n)
: Sets a (float) timeout on I/O operations.
For ease of use, you may also pass in an address (as a tuple) or a hoststring as the
sock
argument. (A host string is a hostname with anoptional port (separated by":"
) which will be converted into atuple of(hostname, port)
.) A socket will be connected to thisaddress and used for communication. Exceptions from thesocket
call may be thrown in this case.Note
Modifying the the window and packet sizes might have adverseeffects on your channels created from this transport. The defaultvalues are the same as in the OpenSSH code base and have beenbattle tested.
Parameters: - sock (socket) – a socket or socket-like object to create the session over.
- default_window_size (int) – sets the default window size on the transport. (defaults to2097152)
- default_max_packet_size (int) – sets the default max packet size on the transport. (defaults to32768)
- gss_kex (bool) – Whether to enable GSSAPI key exchange when GSSAPI is in play.Default:
False
. - gss_deleg_creds (bool) – Whether to enable GSSAPI credential delegation when GSSAPI is inplay. Default:
True
.
Changed in version 1.15: Added the
default_window_size
anddefault_max_packet_size
arguments.Changed in version 1.15: Added the
gss_kex
andgss_deleg_creds
kwargs.
__repr__
()¶Returns a string representation of this object, for debugging.
accept
(timeout=None)¶Return the next channel opened by the client over this transport, inserver mode. If no channel is opened before the given timeout,
None
is returned.Parameters: timeout (int) – seconds to wait for a channel, or None
to wait foreverReturns: a new Channel opened by the client
add_server_key
(key)¶Add a host key to the list of keys used for server mode. When behavingas a server, the host key is used to sign certain packets during theSSH2 negotiation, so that the client can trust that we are who we saywe are. Because this is used for signing, the key must contain privatekey info, not just the public half. Only one key of each type (RSA orDSS) is kept.
Parameters: key (PKey) – the host key to add, usually an RSAKey or DSSKey.
atfork
()¶Terminate this Transport without closing the session. On posixsystems, if a Transport is open during process forking, both parentand child will share the underlying socket, but only one process canuse the connection (without corrupting the session). Use this methodto clean up a Transport object without disrupting the other process.
New in version 1.5.3.
auth_gssapi_keyex
(username)¶Authenticate to the server with GSS-API/SSPI if GSS-API kex is in use.
Parameters: username (str) – The username to authenticate as. Returns: a list of auth types permissible for the next stage ofauthentication (normally empty) Raises: BadAuthenticationType –if GSS-API Key Exchange was not performed (and no event was passedin) Raises: AuthenticationException –if the authentication failed (and no event was passed in) Raises: SSHException – if there was a network error
auth_gssapi_with_mic
(username, gss_host, gss_deleg_creds)¶Authenticate to the Server using GSS-API / SSPI.
Parameters: Returns: list of auth types permissible for the next stage ofauthentication (normally empty)
Raises: BadAuthenticationType – if gssapi-with-mic isn’tallowed by the server (and no event was passed in)
Raises: AuthenticationException – if the authentication failed (and noevent was passed in)
Raises: SSHException – if there was a network error
auth_interactive
(username, handler, submethods='')¶Authenticate to the server interactively. A handler is used to answerarbitrary questions from the server. On many servers, this is just adumb wrapper around PAM.
This method will block until the authentication succeeds or fails,peroidically calling the handler asynchronously to get answers toauthentication questions. The handler may be called more than onceif the server continues to ask questions.
The handler is expected to be a callable that will handle calls of theform:
handler(title, instructions, prompt_list)
. Thetitle
ismeant to be a dialog-window title, and theinstructions
are userinstructions (both are strings).prompt_list
will be a list ofprompts, each prompt being a tuple of(str, bool)
. The string isthe prompt and the boolean indicates whether the user text should beechoed.A sample call would thus be:
handler('title', 'instructions', [('Password:', False)])
.The handler should return a list or tuple of answers to the server’squestions.
If the server requires multi-step authentication (which is very rare),this method will return a list of auth types permissible for the nextstep. Otherwise, in the normal case, an empty list is returned.
Parameters: Returns: list of auth types permissible for the next stage ofauthentication (normally empty).
Raises: BadAuthenticationType – if public-key authentication isn’tallowed by the server for this user
Raises: AuthenticationException – if the authentication failed
Raises: SSHException – if there was a network error
New in version 1.5.
auth_interactive_dumb
(username, handler=None, submethods='')¶Autenticate to the server interactively but dumber.Just print the prompt and / or instructions to stdout and send backthe response. This is good for situations where partial auth isachieved by key and then the user has to enter a 2fac token.
auth_none
(username)¶Try to authenticate to the server using no authentication at all.This will almost always fail. It may be useful for determining thelist of authentication types supported by the server, by catching theBadAuthenticationType exception raised.
Parameters: username (str) – the username to authenticate as Returns: list of auth types permissible for the next stage ofauthentication (normally empty) Raises: BadAuthenticationType – if “none” authentication isn’t allowedby the server for this user Raises: SSHException – if the authentication failed due to a networkerror New in version 1.5.
auth_password
(username, password, event=None, fallback=True)¶Authenticate to the server using a password. The username and passwordare sent over an encrypted link.
If an
event
is passed in, this method will return immediately, andthe event will be triggered once authentication succeeds or fails. Onsuccess, is_authenticated will returnTrue
. On failure, you mayuse get_exception to get more detailed error information.Since 1.1, if no event is passed, this method will block until theauthentication succeeds or fails. On failure, an exception is raised.Otherwise, the method simply returns.
See AlsoVTY line when configuring SSHCisco IOS in a Nutshell, 2nd EditionCommand-line switches for Microsoft Office productsCommscope Technical Content PortalSince 1.5, if no event is passed and
fallback
isTrue
(thedefault), if the server doesn’t support plain password authenticationbut does support so-called “keyboard-interactive” mode, an attemptwill be made to authenticate using this interactive mode. If it fails,the normal exception will be thrown as if the attempt had never beenmade. This is useful for some recent Gentoo and Debian distributions,which turn off plain password authentication in a misguided beliefthat interactive authentication is “more secure”. (It’s not.)If the server requires multi-step authentication (which is very rare),this method will return a list of auth types permissible for the nextstep. Otherwise, in the normal case, an empty list is returned.
Parameters: - username (str) – the username to authenticate as
- password (basestring) – the password to authenticate with
- event (threading.Event) – an event to trigger when the authentication attempt is complete(whether it was successful or not)
- fallback (bool) –
True
if an attempt at an automated “interactive” password authshould be made if the server doesn’t support normal password auth
Returns: list of auth types permissible for the next stage ofauthentication (normally empty)
Raises: BadAuthenticationType – if password authentication isn’tallowed by the server for this user (and no event was passed in)
Raises: AuthenticationException – if the authentication failed (and noevent was passed in)
Raises: SSHException – if there was a network error
auth_publickey
(username, key, event=None)¶Authenticate to the server using a private key. The key is used tosign data from the server, so it must include the private part.
If an
event
is passed in, this method will return immediately, andthe event will be triggered once authentication succeeds or fails. Onsuccess, is_authenticated will returnTrue
. On failure, you mayuse get_exception to get more detailed error information.Since 1.1, if no event is passed, this method will block until theauthentication succeeds or fails. On failure, an exception is raised.Otherwise, the method simply returns.
If the server requires multi-step authentication (which is very rare),this method will return a list of auth types permissible for the nextstep. Otherwise, in the normal case, an empty list is returned.
Parameters: - username (str) – the username to authenticate as
- key (PKey) – the private key to authenticate with
- event (threading.Event) – an event to trigger when the authentication attempt is complete(whether it was successful or not)
Returns: list of auth types permissible for the next stage ofauthentication (normally empty)
Raises: BadAuthenticationType – if public-key authentication isn’tallowed by the server for this user (and no event was passed in)
Raises: AuthenticationException – if the authentication failed (and noevent was passed in)
Raises: SSHException – if there was a network error
cancel_port_forward
(address, port)¶Ask the server to cancel a previous port-forwarding request. No moreconnections to the given address & port will be forwarded across thisssh connection.
Parameters:
close
()¶Close this session, and any open channels that are tied to it.
connect
(hostkey=None, username='', password=None, pkey=None, gss_host=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, gss_trust_dns=True)¶Negotiate an SSH2 session, and optionally verify the server’s host keyand authenticate using a password or private key. This is a shortcutfor start_client, get_remote_server_key, andTransport.auth_password or Transport.auth_publickey. Use thosemethods if you want more control.
You can use this method immediately after creating a Transport tonegotiate encryption with a server. If it fails, an exception will bethrown. On success, the method will return cleanly, and an encryptedsession exists. You may immediately call open_channel oropen_session to get a Channel object, which is used for datatransfer.
Note
If you fail to supply a password or private key, this method maysucceed, but a subsequent open_channel or open_session call mayfail because you haven’t authenticated yet.
Parameters: - hostkey (PKey) – the host key expected from the server, or
None
if you don’twant to do host key verification. - username (str) – the username to authenticate as.
- password (str) – a password to use for authentication, if you want to use passwordauthentication; otherwise
None
. - pkey (PKey) – a private key to use for authentication, if you want to use privatekey authentication; otherwise
None
. - gss_host (str) – The target’s name in the kerberos database. Default: hostname
- gss_auth (bool) –
True
if you want to use GSS-API authentication. - gss_kex (bool) – Perform GSS-API Key Exchange and user authentication.
- gss_deleg_creds (bool) – Whether to delegate GSS-API client credentials.
- gss_trust_dns – Indicates whether or not the DNS is trusted to securelycanonicalize the name of the host being connected to (default
True
).
Raises: SSHException – if the SSH2 negotiation fails, the host keysupplied by the server is incorrect, or authentication fails.
Changed in version 2.3: Added the
gss_trust_dns
argument.- hostkey (PKey) – the host key expected from the server, or
get_banner
()¶Return the banner supplied by the server upon connect. If no banner issupplied, this method returns
None
.Returns: server supplied banner ( str
), orNone
.New in version 1.13.
get_exception
()¶Return any exception that happened during the last server request.This can be used to fetch more specific error information after usingcalls like start_client. The exception (if any) is cleared afterthis call.
Returns: an exception, or None
if there is no stored exception.New in version 1.1.
get_hexdump
()¶Return
True
if the transport is currently logging hex dumps ofprotocol traffic.Returns: True
if hex dumps are being logged, elseFalse
.New in version 1.4.
get_log_channel
()¶Return the channel name used for this transport’s logging.
Returns: channel name as a str
New in version 1.2.
get_remote_server_key
()¶Return the host key of the server (in client mode).
Note
Previously this call returned a tuple of
(key type, keystring)
. You can get the same effect by calling PKey.get_namefor the key type, andstr(key)
for the key string.Raises: SSHException – if no session is currently active. Returns: public key (PKey) of the remote server
get_security_options
()¶Return a SecurityOptions object which can be used to tweak theencryption algorithms this transport will permit (for encryption,digest/hash operations, public keys, and key exchanges) and the orderof preference for them.
get_server_key
()¶Return the active host key, in server mode. After negotiating with theclient, this method will return the negotiated host key. If only onetype of host key was set with add_server_key, that’s the only keythat will ever be returned. But in cases where you have set more thanone type of host key (for example, an RSA key and a DSS key), the keytype will be negotiated by the client, and this method will return thekey of the type agreed on. If the host key has not been negotiatedyet,
None
is returned. In client mode, the behavior is undefined.Returns: host key (PKey) of the type negotiated by the client, or None
.
get_username
()¶Return the username this connection is authenticated for. If thesession is not authenticated (or authentication failed), this methodreturns
None
.Returns: username that was authenticated (a str
), orNone
.
getpeername
()¶Return the address of the remote side of this Transport, if possible.
See AlsoTelnet vs SSHThis is effectively a wrapper around
getpeername
on the underlyingsocket. If the socket-like object has nogetpeername
method, then("unknown", 0)
is returned.Returns: the address of the remote host, if known, as a (str, int)
tuple.
global_request
(kind, data=None, wait=True)¶Make a global request to the remote host. These are normallyextensions to the SSH2 protocol.
Parameters: Returns: a Message containing possible additional data if the request wassuccessful (or an empty Message if
wait
wasFalse
);None
if the request was denied.
is_active
()¶Return true if this session is active (open).
Returns: True if the session is still active (open); False if the session isclosed
is_authenticated
()¶Return true if this session is active and authenticated.
Returns: True if the session is still open and has been authenticatedsuccessfully; False if authentication failed and/or the session isclosed.
- static
load_server_moduli
(filename=None)¶ (optional)Load a file of prime moduli for use in doing group-exchange keynegotiation in server mode. It’s a rather obscure option and can besafely ignored.
In server mode, the remote client may request “group-exchange” keynegotiation, which asks the server to send a random prime number thatfits certain criteria. These primes are pretty difficult to compute,so they can’t be generated on demand. But many systems contain a fileof suitable primes (usually named something like
/etc/ssh/moduli
).If you call load_server_moduli and it returnsTrue
, then thisfile of primes has been loaded and we will support “group-exchange” inserver mode. Otherwise server mode will just claim that it doesn’tsupport that method of key negotiation.Parameters: filename (str) – optional path to the moduli file, if you happen to know that it’snot in a standard location. Returns: True if a moduli file was successfully loaded; False otherwise. Note
This has no effect when used in client mode.
open_channel
(kind, dest_addr=None, src_addr=None, window_size=None, max_packet_size=None, timeout=None)¶Request a new channel to the server. Channels aresocket-like objects used for the actual transfer of data across thesession. You may only request a channel after negotiating encryption(using connect or start_client) and authenticating.
Note
Modifying the the window and packet sizes might have adverseeffects on the channel created. The default values are the sameas in the OpenSSH code base and have been battle tested.
Parameters: - kind (str) – the kind of channel requested (usually
"session"
,"forwarded-tcpip"
,"direct-tcpip"
, or"x11"
) - dest_addr (tuple) – the destination address (address + port tuple) of this portforwarding, if
kind
is"forwarded-tcpip"
or"direct-tcpip"
(ignored for other channel types) - src_addr – the source address of this port forwarding, if
kind
is"forwarded-tcpip"
,"direct-tcpip"
, or"x11"
- window_size (int) – optional window size for this session.
- max_packet_size (int) – optional max packet size for this session.
- timeout (float) – optional timeout opening a channel, default 3600s (1h)
Returns: a new Channel on success
Raises: SSHException – if the request is rejected, the session endsprematurely or there is a timeout openning a channel
Changed in version 1.15: Added the
window_size
andmax_packet_size
arguments.- kind (str) – the kind of channel requested (usually
open_forward_agent_channel
()¶Request a new channel to the client, of type
"[email protected]"
.This is just an alias for
open_channel('[email protected]')
.Returns: a new Channel Raises: SSHException –if the request is rejected or the session ends prematurely
open_forwarded_tcpip_channel
(src_addr, dest_addr)¶Request a new channel back to the client, of type
forwarded-tcpip
.This is used after a client has requested port forwarding, for sendingincoming connections back to the client.
Parameters: - src_addr – originator’s address
- dest_addr – local (server) connected address
open_session
(window_size=None, max_packet_size=None, timeout=None)¶Request a new channel to the server, of type
"session"
. This isjust an alias for calling open_channel with an argument of"session"
.Note
Modifying the the window and packet sizes might have adverseeffects on the session created. The default values are the sameas in the OpenSSH code base and have been battle tested.
Parameters: Returns: a new Channel
Raises: SSHException – if the request is rejected or the session endsprematurely
Changed in version 1.13.4/1.14.3/1.15.3: Added the
timeout
argument.Changed in version 1.15: Added the
window_size
andmax_packet_size
arguments.
open_sftp_client
()¶Create an SFTP client channel from an open transport. On success, anSFTP session will be opened with the remote host, and a newSFTPClient object will be returned.
Returns: a new SFTPClient referring to an sftp session (channel) acrossthis transport
open_x11_channel
(src_addr=None)¶Request a new channel to the client, of type
"x11"
. Thisis just an alias foropen_channel('x11', src_addr=src_addr)
.Parameters: src_addr (tuple) – the source address ( (str, int)
) of the x11 server (port is thex11 port, ie. 6010)Returns: a new Channel Raises: SSHException – if the request is rejected or the session endsprematurely
renegotiate_keys
()¶Force this session to switch to new keys. Normally this is doneautomatically after the session hits a certain number of packets orbytes sent or received, but this method gives you the option of forcingnew keys whenever you want. Negotiating new keys causes a pause intraffic both ways as the two sides swap keys and do computations. Thismethod returns when the session has switched to new keys.
Raises: SSHException – if the key renegotiation failed (which causesthe session to end)
request_port_forward
(address, port, handler=None)¶Ask the server to forward TCP connections from a listening port onthe server, across this SSH session.
If a handler is given, that handler is called from a different threadwhenever a forwarded connection arrives. The handler parameters are:
handler( channel, (origin_addr, origin_port), (server_addr, server_port),)
where
server_addr
andserver_port
are the address and port thatthe server was listening on.If no handler is set, the default behavior is to send new incomingforwarded connections into the accept queue, to be picked up viaaccept.
Parameters: Returns: the port number (
int
) allocated by the serverRaises: SSHException – if the server refused the TCP forward request
send_ignore
(byte_count=None)¶Send a junk packet across the encrypted link. This is sometimes usedto add “noise” to a connection to confuse would-be attackers. It canalso be used as a keep-alive for long lived connections traversingfirewalls.
Parameters: byte_count (int) – the number of random bytes to send in the payload of the ignoredpacket – defaults to a random number from 10 to 41.
set_gss_host
(gss_host, trust_dns=True, gssapi_requested=True)¶Normalize/canonicalize
self.gss_host
depending on various factors.Parameters: - gss_host (str) – The explicitly requested GSS-oriented hostname to connect to (i.e.what the host’s name is in the Kerberos database.) Defaults to
self.hostname
(which will be the ‘real’ target hostname and/orhost portion of given socket object.) - trust_dns (bool) – Indicates whether or not DNS is trusted; if true, DNS will be usedto canonicalize the GSS hostname (which again will either be
gss_host
or the transport’s default hostname.)(Defaults to True due to backwards compatibility.) - gssapi_requested (bool) – Whether GSSAPI key exchange or authentication was even requested.If not, this is a no-op and nothing happens(and
self.gss_host
is not set.)(Defaults to True due to backwards compatibility.)
Returns: None
.- gss_host (str) – The explicitly requested GSS-oriented hostname to connect to (i.e.what the host’s name is in the Kerberos database.) Defaults to
set_hexdump
(hexdump)¶Turn on/off logging a hex dump of protocol traffic at DEBUG level inthe logs. Normally you would want this off (which is the default),but if you are debugging something, it may be useful.
Parameters: hexdump (bool) – True
to log protocol traffix (in hex) to the log;False
otherwise.
set_keepalive
(interval)¶Turn on/off keepalive packets (default is off). If this is set, after
interval
seconds without sending any data over the connection, a“keepalive” packet will be sent (and ignored by the remote host). Thiscan be useful to keep connections alive over a NAT, for example.Parameters: interval (int) – seconds to wait before sending a keepalive packet (or0 to disable keepalives).
set_log_channel
(name)¶Set the channel for this transport’s logging. The default is
"paramiko.transport"
but it can be set to anything you want. (Seethelogging
module for more info.) SSH Channels will log to asub-channel of the one specified.Parameters: name (str) – new channel name for logging New in version 1.1.
set_subsystem_handler
(name, handler, *larg, **kwarg)¶Set the handler class for a subsystem in server mode. If a requestfor this subsystem is made on an open ssh channel later, this handlerwill be constructed and called – see SubsystemHandler for moredetailed documentation.
Any extra parameters (including keyword arguments) are saved andpassed to the SubsystemHandler constructor later.
Parameters: - name (str) – name of the subsystem.
- handler – subclass of SubsystemHandler that handles this subsystem.
start_client
(event=None, timeout=None)¶Negotiate a new SSH2 session as a client. This is the first step aftercreating a new Transport. A separate thread is created for protocolnegotiation.
If an event is passed in, this method returns immediately. Whennegotiation is done (successful or not), the given
Event
willbe triggered. On failure, is_active will returnFalse
.(Since 1.4) If
event
isNone
, this method will not return untilnegotiation is done. On success, the method returns normally.Otherwise an SSHException is raised.After a successful negotiation, you will usually want to authenticate,calling auth_password orauth_publickey.
Note
connect is a simpler method for connecting as a client.
Note
After calling this method (or start_server or connect), youshould no longer directly read from or write to the original socketobject.
Parameters: - event (threading.Event) – an event to trigger when negotiation is complete (optional)
- timeout (float) – a timeout, in seconds, for SSH2 session negotiation (optional)
Raises: SSHException – if negotiation fails (and no
event
waspassed in)
start_server
(event=None, server=None)¶Negotiate a new SSH2 session as a server. This is the first step aftercreating a new Transport and setting up your server host key(s). Aseparate thread is created for protocol negotiation.
If an event is passed in, this method returns immediately. Whennegotiation is done (successful or not), the given
Event
willbe triggered. On failure, is_active will returnFalse
.(Since 1.4) If
event
isNone
, this method will not return untilnegotiation is done. On success, the method returns normally.Otherwise an SSHException is raised.After a successful negotiation, the client will need to authenticate.Override the methods get_allowed_auths, check_auth_none, check_auth_password, and check_auth_publickey in the given
server
objectto control the authentication process.After a successful authentication, the client should request to open achannel. Override check_channel_request in the given
server
object to allow channels to be opened.Note
After calling this method (or start_client or connect), youshould no longer directly read from or write to the original socketobject.
Parameters: - event (threading.Event) – an event to trigger when negotiation is complete.
- server (ServerInterface) – an object used to perform authentication and create channels
Raises: SSHException – if negotiation fails (and no
event
waspassed in)
use_compression
(compress=True)¶Turn on/off compression. This will only have an affect before startingthe transport (ie before calling connect, etc). By default,compression is off since it negatively affects interactive sessions.
Parameters: compress (bool) – True
to ask the remote client/server to compress traffic;False
to refuse compressionNew in version 1.5.2.