Struct Session

Source
pub struct Session { /* private fields */ }
Expand description

An SSH session, typically representing one TCP connection.

All other structures are based on an SSH session and cannot outlive a session. Sessions are created and then have the TCP socket handed to them (via the set_tcp_stream method).

Session, and any objects its methods return, hold a reference to the underlying SSH session. You may clone Session to obtain another handle referencing the same session, and create multiple Channel and Stream objects from that same underlying session, which can all be passed across thread boundaries (they are Send and Sync). These are all related objects and are internally synchronized via a Mutex to make it safe to pass them around in this way.

This means that a blocking read from a Channel or Stream will block all other calls on objects created from the same underlying Session. If you need the ability to perform concurrent operations then you will need to create separate Session instances, or employ non-blocking mode.

Implementations§

Source§

impl Session

Source

pub fn new() -> Result<Session, Error>

Initializes an SSH session object.

This function does not associate the session with a remote connection just yet. Various configuration options can be set such as the blocking mode, compression, sigpipe, the banner, etc. To associate this session with a TCP connection, use the set_tcp_stream method pass in an already-established TCP socket, and then follow up with a call to handshake to perform the ssh protocol handshake.

Source

pub fn set_banner(&self, banner: &str) -> Result<(), Error>

Set the SSH protocol banner for the local client

Set the banner that will be sent to the remote host when the SSH session is started with handshake(). This is optional; a banner corresponding to the protocol and libssh2 version will be sent by default.

Source

pub fn set_allow_sigpipe(&self, block: bool)

Flag indicating whether SIGPIPE signals will be allowed or blocked.

By default (on relevant platforms) this library will attempt to block and catch SIGPIPE signals. Setting this flag to true will cause the library to not attempt to block SIGPIPE from the underlying socket layer.

Source

pub fn set_compress(&self, compress: bool)

Flag indicating whether this library will attempt to negotiate compression.

If set - before the connection negotiation is performed - libssh2 will try to negotiate compression enabling for this connection. By default libssh2 will not attempt to use compression.

Source

pub fn set_blocking(&self, blocking: bool)

Set or clear blocking mode on session

This will instantly affect any channels associated with this session. If a read is performed on a session with no data currently available, a blocking session will wait for data to arrive and return what it receives. A non-blocking session will return immediately with an empty buffer. If a write is performed on a session with no room for more data, a blocking session will wait for room. A non-blocking session will return immediately without writing anything.

Source

pub fn is_blocking(&self) -> bool

Returns whether the session was previously set to nonblocking.

Source

pub fn set_timeout(&self, timeout_ms: u32)

Set timeout for blocking functions.

Set the timeout in milliseconds for how long a blocking the libssh2 function calls may wait until they consider the situation an error and return an error.

By default or if you set the timeout to zero, libssh2 has no timeout for blocking functions.

Source

pub fn timeout(&self) -> u32

Returns the timeout, in milliseconds, for how long blocking calls may wait until they time out.

A timeout of 0 signifies no timeout.

Source

pub fn handshake(&mut self) -> Result<(), Error>

Begin transport layer protocol negotiation with the connected host.

You must call this after associating the session with a tcp stream via the set_tcp_stream function.

Source

pub fn set_tcp_stream<S: 'static + AsRawFd>(&mut self, stream: S)

The session takes ownership of the stream provided. You may use the AsRawFd (unix) or AsRawSocket (windows) traits to obtain the raw fd later if required.

It is also highly recommended that the stream provided is not used concurrently elsewhere for the duration of this session as it may interfere with the protocol.

Source

pub fn userauth_password( &self, username: &str, password: &str, ) -> Result<(), Error>

Attempt basic password authentication.

Note that many SSH servers which appear to support ordinary password authentication actually have it disabled and use Keyboard Interactive authentication (routed via PAM or another authentication backed) instead.

Source

pub fn userauth_keyboard_interactive<P: KeyboardInteractivePrompt>( &self, username: &str, prompter: &mut P, ) -> Result<(), Error>

Attempt keyboard interactive authentication.

You must supply a callback function to

Source

pub fn userauth_agent(&self, username: &str) -> Result<(), Error>

Attempt to perform SSH agent authentication.

This is a helper method for attempting to authenticate the current connection with the first public key found in an SSH agent. If more control is needed than this method offers, it is recommended to use agent directly to control how the identity is found.

Source

pub fn userauth_pubkey_file( &self, username: &str, pubkey: Option<&Path>, privatekey: &Path, passphrase: Option<&str>, ) -> Result<(), Error>

Attempt public key authentication using a PEM encoded private key file stored on disk.

Source

pub fn userauth_pubkey_memory( &self, username: &str, pubkeydata: Option<&str>, privatekeydata: &str, passphrase: Option<&str>, ) -> Result<(), Error>

Attempt public key authentication using a PEM encoded private key from memory. Public key is computed from private key if none passed. This is available with openssl enabled (Required for Unix, or with vendored-openssl or openssl-on-win32 features).

Source

pub fn userauth_hostbased_file( &self, username: &str, publickey: &Path, privatekey: &Path, passphrase: Option<&str>, hostname: &str, local_username: Option<&str>, ) -> Result<(), Error>

Source

pub fn authenticated(&self) -> bool

Indicates whether or not the named session has been successfully authenticated.

Source

pub fn auth_methods(&self, username: &str) -> Result<&str, Error>

Send a SSH_USERAUTH_NONE request to the remote host.

Unless the remote host is configured to accept none as a viable authentication scheme (unlikely), it will return SSH_USERAUTH_FAILURE along with a listing of what authentication schemes it does support. In the unlikely event that none authentication succeeds, this method with return an error. This case may be distinguished from a failing case by examining the return value of the authenticated method.

The return value is a comma-separated string of supported auth schemes, and may be an empty string.

Source

pub fn userauth_banner(&self) -> Result<Option<&str>, Error>

Retrieve banner message from server, if available.

When no such message is sent by server or if no authentication attempt has been made, this function returns LIBSSH2_ERROR_MISSING_AUTH_BANNER.

The return value is the userauth banner or None or an Error

Source

pub fn method_pref( &self, method_type: MethodType, prefs: &str, ) -> Result<(), Error>

Set preferred key exchange method

The preferences provided are a comma delimited list of preferred methods to use with the most preferred listed first and the least preferred listed last. If a method is listed which is not supported by libssh2 it will be ignored and not sent to the remote host during protocol negotiation.

Source

pub fn methods(&self, method_type: MethodType) -> Option<&str>

Return the currently active algorithms.

Returns the actual method negotiated for a particular transport parameter. May return None if the session has not yet been started.

Source

pub fn supported_algs( &self, method_type: MethodType, ) -> Result<Vec<&'static str>, Error>

Get list of supported algorithms.

Source

pub fn agent(&self) -> Result<Agent, Error>

Init an ssh-agent handle.

The returned agent will still need to be connected manually before use.

Source

pub fn known_hosts(&self) -> Result<KnownHosts, Error>

Init a collection of known hosts for this session.

Returns the handle to an internal representation of a known host collection.

Source

pub fn channel_session(&self) -> Result<Channel, Error>

Establish a new session-based channel.

This method is commonly used to create a channel to execute commands over or create a new login shell.

Source

pub fn channel_direct_tcpip( &self, host: &str, port: u16, src: Option<(&str, u16)>, ) -> Result<Channel, Error>

Tunnel a TCP connection through an SSH session.

Tunnel a TCP/IP connection through the SSH transport via the remote host to a third party. Communication from the client to the SSH server remains encrypted, communication from the server to the 3rd party host travels in cleartext.

The optional src argument is the host/port to tell the SSH server where the connection originated from.

The Channel returned represents a connection between this host and the specified remote host.

Source

pub fn channel_direct_streamlocal( &self, socket_path: &str, src: Option<(&str, u16)>, ) -> Result<Channel, Error>

Tunnel a Unix domain socket connection through an SSH session.

Tunnel a UNIX socket connection through the SSH transport via the remote host to a third party. Communication from the client to the SSH server remains encrypted, communication from the server to the 3rd party host travels in cleartext.

The optional src argument is the host/port to tell the SSH server where the connection originated from.

The Channel returned represents a connection between this host and the specified remote host.

Source

pub fn channel_forward_listen( &self, remote_port: u16, host: Option<&str>, queue_maxsize: Option<u32>, ) -> Result<(Listener, u16), Error>

Instruct the remote SSH server to begin listening for inbound TCP/IP connections.

New connections will be queued by the library until accepted by the accept method on the returned Listener.

Source

pub fn scp_recv(&self, path: &Path) -> Result<(Channel, ScpFileStat), Error>

Request a file from the remote host via SCP.

The path specified is a path on the remote host which will attempt to be sent over the returned channel. Some stat information is also returned about the remote file to prepare for receiving the file.

Source

pub fn scp_send( &self, remote_path: &Path, mode: i32, size: u64, times: Option<(u64, u64)>, ) -> Result<Channel, Error>

Send a file to the remote host via SCP.

The remote_path provided will be the remote file name. The times argument is a tuple of (mtime, atime), and will default to the remote host’s current time if not specified.

The size of the file, size, must be known ahead of time before transmission.

Source

pub fn sftp(&self) -> Result<Sftp, Error>

Open a channel and initialize the SFTP subsystem.

Although the SFTP subsystem operates over the same type of channel as those exported by the Channel API, the protocol itself implements its own unique binary packet protocol which must be managed with the methods on Sftp.

Source

pub fn channel_open( &self, channel_type: &str, window_size: u32, packet_size: u32, message: Option<&str>, ) -> Result<Channel, Error>

Allocate a new channel for exchanging data with the server.

This is typically not called directly but rather through channel_session, channel_direct_tcpip, or channel_forward_listen.

Source

pub fn banner(&self) -> Option<&str>

Get the remote banner

Once the session has been setup and handshake() has completed successfully, this function can be used to get the server id from the banner each server presents.

May return None on invalid utf-8 or if an error has occurred.

Source

pub fn banner_bytes(&self) -> Option<&[u8]>

See banner.

Will only return None if an error has occurred.

Source

pub fn host_key(&self) -> Option<(&[u8], HostKeyType)>

Get the remote key.

Returns None if something went wrong.

Source

pub fn host_key_hash(&self, hash: HashType) -> Option<&[u8]>

Returns the computed digest of the remote system’s hostkey.

The bytes returned are the raw hash, and are not printable. If the hash is not yet available None is returned.

Source

pub fn set_keepalive(&self, want_reply: bool, interval: u32)

Set how often keepalive messages should be sent.

The want_reply argument indicates whether the keepalive messages should request a response from the server.

The interval argument is number of seconds that can pass without any I/O, use 0 (the default) to disable keepalives. To avoid some busy-loop corner-cases, if you specify an interval of 1 it will be treated as 2.

Source

pub fn keepalive_send(&self) -> Result<u32, Error>

Send a keepalive message if needed.

Returns how many seconds you can sleep after this call before you need to call it again.

Source

pub fn disconnect( &self, reason: Option<DisconnectCode>, description: &str, lang: Option<&str>, ) -> Result<(), Error>

Terminate the transport layer.

Send a disconnect message to the remote host associated with session, along with a reason symbol and a verbose description.

Note that this does not close the underlying socket.

Source

pub fn block_directions(&self) -> BlockDirections

Returns the blocked io directions that the application needs to wait for.

This function should be used after an error of type WouldBlock is returned to find out the socket events the application has to wait for.

Source

pub fn trace(&self, bitmask: TraceFlags)

Sets the trace level for the session.

Trait Implementations§

Source§

impl AsRawFd for Session

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
Source§

impl Clone for Session

Source§

fn clone(&self) -> Session

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.