Struct Session

Source
pub struct Session {
    pub addr: SocketAddr,
    /* private fields */
}
Expand description

An established SSH session.

See ssh2::Session in general, and ssh2::Session#channel_session specifically, for how to execute commands on the remote host.

To execute a command and get its STDOUT output, use Session#cmd.

Fields§

§addr: SocketAddr

The connected address

Implementations§

Source§

impl Session

Source

pub fn connect( log: &Logger, username: &str, addr: SocketAddr, key: Option<&Path>, timeout: Option<Duration>, ) -> Result<Self, Error>

Connect to the remote machine at addr, using user username.

Analogous to ssh -i <key> <username>@<addr>.

If timeout is None, will block for a TCP response forever.

If key is None, attempts to use ssh-agent authentication.

Source

pub fn cmd_raw(&self, cmd: &str) -> Result<(Vec<u8>, Vec<u8>), Error>

Issue the given command and return the command’s raw stdout and stderr.

Source

pub fn upload(&self, local_src: &Path, remote_dst: &Path) -> Result<(), Error>

Copy a file from the local machine to the remote host.

Both remote and local paths can be absolute or relative.

    use std::path::Path;
    ssh.upload(
        Path::new("build/output.tar.gz"), // on the local machine
        Path::new("/srv/output.tar.gz"), // on the remote machine
    )?;
Source

pub fn cmd(&self, cmd: &str) -> Result<(String, String), Error>

Issue the given command and return the command’s stdout and stderr.

Source

pub fn download(&self, remote_src: &Path, local_dst: &Path) -> Result<(), Error>

Copy a file from the remote host to the local machine.

Both remote and local paths can be absolute or relative.

    use std::path::Path;
    ssh.download(
        Path::new("/etc/hostname"), // on the remote machine
        Path::new("remote-hostname"), // on the local machine
    )?;

Methods from Deref<Target = Session>§

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>(&mut self, stream: S)
where S: 'static + AsRawFd,

The session takes ownership of the stream provided. You may use the tcp_stream() method to obtain the raw fd later.

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>( &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 only for unix targets, as it relies on openssl. It is therefore recommended to use #[cfg(unix)] or otherwise test for the unix compliation target when using this function.

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

Trait Implementations§

Source§

impl Debug for Session

Source§

fn fmt(&self, formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for Session

Source§

type Target = Session

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for Session

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl From<Session> for Session

Source§

fn from(s: Session) -> Self

Converts to this type from the input type.

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> 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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.