Python Ssh

Posted : admin On 1/26/2022

One of the typical scenarios where sshtunnel is helpful is depicted in the figure below. User may need to connect a port of a remote server (i.e. 8080) where only SSH port (usually port 22) is reachable. It's a module for Python 2.7/3.4+ that implements the SSH2 protocol for secure (encrypted and authenticated) connections to remote machines. Unlike SSL (aka TLS), SSH2 protocol does not require hierarchical certificates signed by a powerful central authority.

  1. Python Ssh Tunnel
  2. Python Ssh Client
  3. Python Sshlib
  4. Python Ssh Tunnel
  5. Python Ssh Client
  6. Python Ssh Client

Abstraction for an SSH2 channel.

class paramiko.channel.Channel(chanid)

A secure tunnel across an SSH Transport. A Channel is meant to behavelike a socket, and has an API that should be indistinguishable from thePython socket API.

Because SSH2 has a windowing kind of flow control, if you stop reading datafrom a Channel and its buffer fills up, the server will be unable to sendyou any more data until you read some of it. (This won’t affect otherchannels on the same transport – all channels on a single transport areflow-controlled independently.) Similarly, if the server isn’t readingdata you send, calls to send may block, unless you set a timeout. Thisis exactly like a normal network socket, so it shouldn’t be too surprising.

Instances of this class may be used as context managers.

__init__(chanid)

Create a new channel. The channel is not associated with anyparticular session or Transport until the Transport attaches it.Normally you would only call this method from the constructor of asubclass of Channel.

Parameters:chanid (int) – the ID of this channel, as passed by an existing Transport.
__repr__()

Return a string representation of this object, for debugging.

close()

Close the channel. All future read/write operations on the channelwill fail. The remote end will receive no more data (after queued datais flushed). Channels are automatically closed when their Transportis closed or when they are garbage collected.

exec_command(command)

Execute a command on the server. If the server allows it, the channelwill then be directly connected to the stdin, stdout, and stderr ofthe command being executed.

When the command finishes executing, the channel will be closed andcan’t be reused. You must open a new channel if you wish to executeanother command.

Parameters:command (str) – a shell command to execute.
Raises:SSHException – if the request was rejected or the channel wasclosed
exit_status_ready()

Return true if the remote process has exited and returned an exitstatus. You may use this to poll the process status if you don’twant to block in recv_exit_status. Note that the server may notreturn an exit status in some cases (like bad servers).

Returns:True if recv_exit_status will return immediately, elseFalse.
fileno()
Python ssh2

Returns an OS-level file descriptor which can be used for polling, butbut not for reading or writing. This is primarily to allow Python’sselect module to work.

The first time fileno is called on a channel, a pipe is created tosimulate real OS-level file descriptor (FD) behavior. Because of this,two OS-level FDs are created, which will use up FDs faster than normal.(You won’t notice this effect unless you have hundreds of channelsopen at the same time.)

Returns:an OS-level file descriptor (int)

Warning

This method causes channel reads to be slightly less efficient.

get_id()

Return the int ID # for this channel.

The channel ID is unique across a Transport and usually a smallnumber. It’s also the number passed toServerInterface.check_channel_request when determining whether toaccept a channel request in server mode.

get_name()

Get the name of this channel that was previously set by set_name.

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

Request a pseudo-terminal from the server. This is usually used rightafter creating a client channel, to ask the server to provide somebasic terminal semantics for a shell invoked with invoke_shell.It isn’t necessary (or desirable) to call this method if you’re goingto execute a single command with exec_command.

Parameters:
  • term (str) – the terminal type to emulate(for example, 'vt100')
  • width (int) – width (in characters) of the terminal screen
  • height (int) – height (in characters) of the terminal screen
  • width_pixels (int) – width (in pixels) of the terminal screen
  • height_pixels (int) – height (in pixels) of the terminal screen
Raises:

SSHException – if the request was rejected or the channel wasclosed

get_transport()

Return the Transport associated with this channel.

getpeername()

Return the address of the remote side of this Channel, if possible.

This simply wraps Transport.getpeername, used to provide enough of asocket-like interface to allow asyncore to work. (asyncore likes tocall 'getpeername'.)

gettimeout()

Returns the timeout in seconds (as a float) associated with socketoperations, or None if no timeout is set. This reflects the lastcall to setblocking or settimeout.

invoke_shell()

Request an interactive shell session on this channel. If the serverallows it, the channel will then be directly connected to the stdin,stdout, and stderr of the shell.

Normally you would call get_pty before this, in which case theshell will operate through the pty, and the channel will be connectedto the stdin and stdout of the pty.

When the shell exits, the channel will be closed and can’t be reused.You must open a new channel if you wish to open another shell.

Raises:SSHException – if the request was rejected or the channel wasclosed
invoke_subsystem(subsystem)

Request a subsystem on the server (for example, sftp). If theserver allows it, the channel will then be directly connected to therequested subsystem.

When the subsystem finishes, the channel will be closed and can’t bereused.

Parameters:subsystem (str) – name of the subsystem being requested.
Raises:SSHException – if the request was rejected or the channel wasclosed
makefile(*params)

Return a file-like object associated with this channel. The optionalmode and bufsize arguments are interpreted the same way as bythe built-in file() function in Python.

Returns:ChannelFile object which can be used for Python file I/O.
makefile_stderr(*params)

Return a file-like object associated with this channel’s stderrstream. Only channels using exec_command or invoke_shellwithout a pty will ever have data on the stderr stream.

The optional mode and bufsize arguments are interpreted thesame way as by the built-in file() function in Python. For aclient, it only makes sense to open this file for reading. For aserver, it only makes sense to open this file for writing.

Returns:ChannelStderrFile object which can be used for Python file I/O.
makefile_stdin(*params)

Return a file-like object associated with this channel’s stdinstream.

The optional mode and bufsize arguments are interpreted thesame way as by the built-in file() function in Python. For aclient, it only makes sense to open this file for writing. For aserver, it only makes sense to open this file for reading.

Returns:ChannelStdinFile object which can be used for Python file I/O.

New in version 2.6.

recv(nbytes)

Receive data from the channel. The return value is a stringrepresenting the data received. The maximum amount of data to bereceived at once is specified by nbytes. If a string oflength zero is returned, the channel stream has closed.

Parameters:nbytes (int) – maximum number of bytes to read.
Returns:received data, as a str/bytes.
Raises:socket.timeout – if no data is ready before the timeout set by settimeout.
recv_exit_status()

Return the exit status from the process on the server. This ismostly useful for retrieving the results of an exec_command.If the command hasn’t finished yet, this method will wait untilit does, or until the channel is closed. If no exit status isprovided by the server, -1 is returned.

Warning

In some situations, receiving remote output larger than the currentTransport or session’s window_size (e.g. that set by thedefault_window_size kwarg for Transport.__init__) will causerecv_exit_status to hang indefinitely if it is called prior to asufficiently large Channel.recv (or if there are no threadscalling Channel.recv in the background).

In these cases, ensuring that recv_exit_status is called afterChannel.recv (or, again, using threads) can avoid the hang.

Returns:the exit code (as an int) of the process on the server.
recv_ready()

Returns true if data is buffered and ready to be read from thischannel. A False result does not mean that the channel has closed;it means you may need to wait before more data arrives.

Returns:True if a recv call on this channel would immediately returnat least one byte; False otherwise.
recv_stderr(nbytes)

Receive data from the channel’s stderr stream. Only channels usingexec_command or invoke_shell without a pty will ever have dataon the stderr stream. The return value is a string representing thedata received. The maximum amount of data to be received at once isspecified by nbytes. If a string of length zero is returned, thechannel stream has closed.

Parameters:nbytes (int) – maximum number of bytes to read.
Returns:received data as a str
Raises:socket.timeout – if no data is ready before the timeout set bysettimeout.
Python Ssh

New in version 1.1.

recv_stderr_ready()

Returns true if data is buffered and ready to be read from thischannel’s stderr stream. Only channels using exec_command orinvoke_shell without a pty will ever have data on the stderrstream.

Returns:True if a recv_stderr call on this channel would immediatelyreturn at least one byte; False otherwise.
request_forward_agent(handler)

Request for a forward SSH Agent on this channel.This is only valid for an ssh-agent from OpenSSH !!!

Parameters:handler – a required callable handler to use for incoming SSH Agentconnections
Returns:True if we are ok, else False(at that time we always return ok)
Raises:SSHException in case of channel problem.
request_x11(screen_number=0, auth_protocol=None, auth_cookie=None, single_connection=False, handler=None)

Request an x11 session on this channel. If the server allows it,further x11 requests can be made from the server to the client,when an x11 application is run in a shell session.

From RFC 4254:

If you omit the auth_cookie, a new secure random 128-bit value will begenerated, used, and returned. You will need to use this value toverify incoming x11 requests and replace them with the actual localx11 cookie (which requires some knowledge of the x11 protocol).

If a handler is passed in, the handler is called from another threadwhenever a new x11 connection arrives. The default handler queues upincoming x11 connections, which may be retrieved usingTransport.accept. The handler’s calling signature is:

Parameters:
  • screen_number (int) – the x11 screen number (0, 10, etc.)
  • auth_protocol (str) – the name of the X11 authentication method used; if none is given,'MIT-MAGIC-COOKIE-1' is used
  • auth_cookie (str) – hexadecimal string containing the x11 auth cookie; if none isgiven, a secure random 128-bit value is generated
  • single_connection (bool) – if True, only a single x11 connection will be forwarded (bydefault, any number of x11 connections can arrive over thissession)
  • handler – an optional callable handler to use for incoming X11 connections
Returns:

the auth_cookie used

resize_pty(width=80, height=24, width_pixels=0, height_pixels=0)

Resize the pseudo-terminal. This can be used to change the width andheight of the terminal emulation created in a previous get_pty call.

Parameters:
  • width (int) – new width (in characters) of the terminal screen
  • height (int) – new height (in characters) of the terminal screen
  • width_pixels (int) – new width (in pixels) of the terminal screen
  • height_pixels (int) – new height (in pixels) of the terminal screen
Raises:

SSHException – if the request was rejected or the channel wasclosed

send(s)

Send data to the channel. Returns the number of bytes sent, or 0 ifthe channel stream is closed. Applications are responsible forchecking that all data has been sent: if only some of the data wastransmitted, the application needs to attempt delivery of the remainingdata.

Parameters:s (str) – data to send
Returns:number of bytes actually sent, as an int
Raises:socket.timeout – if no data could be sent before the timeout setby settimeout.
send_exit_status(status)

Send the exit status of an executed command to the client. (Thisreally only makes sense in server mode.) Many clients expect toget some sort of status code back from an executed command afterit completes.

Parameters:status (int) – the exit code of the process

New in version 1.2.

send_ready()

Returns true if data can be written to this channel without blocking.This means the channel is either closed (so any write attempt wouldreturn immediately) or there is at least one byte of space in theoutbound buffer. If there is at least one byte of space in theoutbound buffer, a send call will succeed immediately and returnthe number of bytes actually written.

Returns:True if a send call on this channel would immediately succeedor fail
send_stderr(s)

Send data to the channel on the “stderr” stream. This is normallyonly used by servers to send output from shell commands – clientswon’t use this. Returns the number of bytes sent, or 0 if the channelstream is closed. Applications are responsible for checking that alldata has been sent: if only some of the data was transmitted, theapplication needs to attempt delivery of the remaining data.

Parameters:s (str) – data to send.
Returns:number of bytes actually sent, as an int.
Raises:socket.timeout – if no data could be sent before the timeout set by settimeout.
sendall(s)

Send data to the channel, without allowing partial results. Unlikesend, this method continues to send data from the given string untileither all data has been sent or an error occurs. Nothing is returned.

Parameters:

s (str) – data to send.

Raises:
  • socket.timeout – if sending stalled for longer than the timeout set by settimeout.
  • socket.error – if an error occurred before the entire string was sent.

Note

If the channel is closed while only part of the data has beensent, there is no way to determine how much data (if any) was sent.This is irritating, but identically follows Python’s API.

sendall_stderr(s)

Send data to the channel’s “stderr” stream, without allowing partialresults. Unlike send_stderr, this method continues to send datafrom the given string until all data has been sent or an error occurs.Nothing is returned.

Parameters:

s (str) – data to send to the client as “stderr” output.

Raises:
  • socket.timeout – if sending stalled for longer than the timeout set by settimeout.
  • socket.error – if an error occurred before the entire string was sent.
set_combine_stderr(combine)

Set whether stderr should be combined into stdout on this channel.The default is False, but in some cases it may be convenient tohave both streams combined.

If this is False, and exec_command is called (or invoke_shellwith no pty), output to stderr will not show up through the recvand recv_ready calls. You will have to use recv_stderr andrecv_stderr_ready to get stderr output.

If this is True, data will never show up via recv_stderr orrecv_stderr_ready.

Parameters:combine (bool) – True if stderr output should be combined into stdout on thischannel.
Returns:the previous setting (a bool).

New in version 1.1.

set_environment_variable(name, value)

Set the value of an environment variable.

Warning

The server may reject this request depending on its AcceptEnvsetting; such rejections will fail silently (which is common clientpractice for this particular request type). Make sure youunderstand your server’s configuration before using!

Parameters:
  • name (str) – name of the environment variable
  • value (str) – value of the environment variable
Raises:

SSHException – if the request was rejected or the channel wasclosed

set_name(name)

Set a name for this channel. Currently it’s only used to set the nameof the channel in logfile entries. The name can be fetched with theget_name method.

Parameters:name (str) – new channel name
setblocking(blocking)

Set blocking or non-blocking mode of the channel: if blocking is 0,the channel is set to non-blocking mode; otherwise it’s set to blockingmode. Initially all channels are in blocking mode.

In non-blocking mode, if a recv call doesn’t find any data, or if asend call can’t immediately dispose of the data, an error exceptionis raised. In blocking mode, the calls block until they can proceed. AnEOF condition is considered “immediate data” for recv, so if thechannel is closed in the read direction, it will never block.

chan.setblocking(0) is equivalent to chan.settimeout(0);chan.setblocking(1) is equivalent to chan.settimeout(None).

Parameters:blocking (int) – 0 to set non-blocking mode; non-0 to set blocking mode.
settimeout(timeout)

Set a timeout on blocking read/write operations. The timeoutargument can be a nonnegative float expressing seconds, or None.If a float is given, subsequent channel read/write operations willraise a timeout exception if the timeout period value has elapsedbefore the operation has completed. Setting a timeout of Nonedisables timeouts on socket operations.

chan.settimeout(0.0) is equivalent to chan.setblocking(0);chan.settimeout(None) is equivalent to chan.setblocking(1).

Parameters:timeout (float) – seconds to wait for a pending read/write operation before raisingsocket.timeout, or None for no timeout.
shutdown(how)

Shut down one or both halves of the connection. If how is 0,further receives are disallowed. If how is 1, further sendsare disallowed. If how is 2, further sends and receives aredisallowed. This closes the stream in one or both directions.

Parameters:how (int) –
0 (stop receiving), 1 (stop sending), or 2 (stop receiving and
sending).
shutdown_read()

Shutdown the receiving side of this socket, closing the stream inthe incoming direction. After this call, future reads on thischannel will fail instantly. This is a convenience method, equivalentto shutdown(0), for people who don’t make it a habit tomemorize unix constants from the 1970s.

shutdown_write()

Shutdown the sending side of this socket, closing the stream inthe outgoing direction. After this call, future writes on thischannel will fail instantly. This is a convenience method, equivalentto shutdown(1), for people who don’t make it a habit tomemorize unix constants from the 1970s.

New in version 1.2.

Python Ssh Tunnel

update_environment(environment)

Python Ssh Client

Updates this channel’s remote shell environment.

Note

Python Sshlib

This operation is additive - i.e. the current environment is notreset before the given environment variables are set.

Warning

Servers may silently reject some environment variables; see thewarning in set_environment_variable for details.

Parameters:environment (dict) – a dictionary containing the name and respective values to set
Raises:SSHException – if any of the environment variables was rejectedby the server or the channel was closed
class paramiko.channel.ChannelFile(channel, mode='r', bufsize=-1)

A file-like wrapper around Channel. A ChannelFile is created by callingChannel.makefile.

Warning

Ssh

To correctly emulate the file object created from a socket’s makefile method, a Channel and itsChannelFile should be able to be closed or garbage-collectedindependently. Currently, closing the ChannelFile does nothing butflush the buffer.

__repr__()

Returns a string representation of this object, for debugging.

class paramiko.channel.ChannelStderrFile(channel, mode='r', bufsize=-1)

A file-like wrapper around Channel stderr.

See Channel.makefile_stderr for details.

Python Ssh Tunnel

class paramiko.channel.ChannelStdinFile(channel, mode='r', bufsize=-1)
Sshpass

A file-like wrapper around Channel stdin.

Python Ssh Client

See Channel.makefile_stdin for details.

paramiko.channel.open_only(func)

Python Ssh Client

Decorator for Channel methods which performs an openness check.

Raises:SSHException – If the wrapped method is called on an unopenedChannel.