pub struct Client { /* private fields */ }Expand description
A ssh connection to a remote server.
After creating a Client by connecting to a remote host,
use execute to send commands and receive results through the connections.
§Examples
use async_ssh2_tokio::{Client, AuthMethod, ServerCheckMethod};
#[tokio::main]
async fn main() -> Result<(), async_ssh2_tokio::Error> {
let mut client = Client::connect(
("10.10.10.2", 22),
"root",
AuthMethod::with_password("root"),
ServerCheckMethod::NoCheck,
).await?;
let result = client.execute("echo Hello SSH").await?;
assert_eq!(result.stdout, "Hello SSH\n");
assert_eq!(result.exit_status, 0);
Ok(())
}Implementations§
Source§impl Client
impl Client
Sourcepub async fn connect(
addr: impl ToSocketAddrsWithHostname,
username: &str,
auth: AuthMethod,
server_check: ServerCheckMethod,
) -> Result<Self, Error>
pub async fn connect( addr: impl ToSocketAddrsWithHostname, username: &str, auth: AuthMethod, server_check: ServerCheckMethod, ) -> Result<Self, Error>
Open a ssh connection to a remote host.
addr is an address of the remote host. Anything which implements
ToSocketAddrsWithHostname trait can be supplied for the address;
ToSocketAddrsWithHostname reimplements all of [ToSocketAddrs];
see this trait’s documentation for concrete examples.
If addr yields multiple addresses, connect will be attempted with
each of the addresses until a connection is successful.
Authentification is tried on the first successful connection and the whole
process aborted if this fails.
Sourcepub async fn connect_with_config(
addr: impl ToSocketAddrsWithHostname,
username: &str,
auth: AuthMethod,
server_check: ServerCheckMethod,
config: Config,
) -> Result<Self, Error>
pub async fn connect_with_config( addr: impl ToSocketAddrsWithHostname, username: &str, auth: AuthMethod, server_check: ServerCheckMethod, config: Config, ) -> Result<Self, Error>
Same as connect, but with the option to specify a non default
russh::client::Config.
pub async fn get_channel(&self) -> Result<Channel<Msg>, Error>
Sourcepub async fn open_direct_tcpip_channel<T: ToSocketAddrsWithHostname, S: Into<Option<SocketAddr>>>(
&self,
target: T,
src: S,
) -> Result<Channel<Msg>, Error>
pub async fn open_direct_tcpip_channel<T: ToSocketAddrsWithHostname, S: Into<Option<SocketAddr>>>( &self, target: T, src: S, ) -> Result<Channel<Msg>, Error>
Open a TCP/IP forwarding channel.
This opens a direct-tcpip channel to the given target.
Sourcepub async fn upload_file<T: AsRef<Path>, U: Into<String>>(
&self,
src_file_path: T,
dest_file_path: U,
) -> Result<(), Error>
pub async fn upload_file<T: AsRef<Path>, U: Into<String>>( &self, src_file_path: T, dest_file_path: U, ) -> Result<(), Error>
Upload a file with sftp to the remote server.
src_file_path is the path to the file on the local machine.
dest_file_path is the path to the file on the remote machine.
Some sshd_config does not enable sftp by default, so make sure it is enabled.
A config line like a Subsystem sftp internal-sftp or
Subsystem sftp /usr/lib/openssh/sftp-server is needed in the sshd_config in remote machine.
Sourcepub async fn download_file<T: AsRef<Path>, U: Into<String>>(
&self,
remote_file_path: U,
local_file_path: T,
) -> Result<(), Error>
pub async fn download_file<T: AsRef<Path>, U: Into<String>>( &self, remote_file_path: U, local_file_path: T, ) -> Result<(), Error>
Download a file from the remote server using sftp.
remote_file_path is the path to the file on the remote machine.
local_file_path is the path to the file on the local machine.
Some sshd_config does not enable sftp by default, so make sure it is enabled.
A config line like a Subsystem sftp internal-sftp or
Subsystem sftp /usr/lib/openssh/sftp-server is needed in the sshd_config in remote machine.
Sourcepub async fn execute(
&self,
command: &str,
) -> Result<CommandExecutedResult, Error>
pub async fn execute( &self, command: &str, ) -> Result<CommandExecutedResult, Error>
Execute a remote command via the ssh connection.
Returns stdout, stderr and the exit code of the command,
packaged in a CommandExecutedResult struct.
If you need the stderr output interleaved within stdout, you should postfix the command with a redirection,
e.g. echo foo 2>&1.
If you dont want any output at all, use something like echo foo >/dev/null 2>&1.
Make sure your commands don’t read from stdin and exit after bounded time.
Can be called multiple times, but every invocation is a new shell context.
Thus cd, setting variables and alike have no effect on future invocations.
Sourcepub async fn execute_streaming(
&self,
command: &str,
ch: Sender<SteamingOutput>,
) -> Result<u32, Error>
👎Deprecated since 0.11.0: Use execute_io with channels directly for more flexibility.
This method will be removed or introduced breaking changes in future versions.
At minimum, SteamingOutput will be renamed to StreamingOutput
pub async fn execute_streaming( &self, command: &str, ch: Sender<SteamingOutput>, ) -> Result<u32, Error>
Execute a remote command via the ssh connection.
Command output is stream to the provided channel. Returns the exit code.
The channel sends SteamingOutput enum variants to distinguish stdout,
stderr and exit code so message arrive interleaved and in the order
they are received. See execute for more details.
Sourcepub async fn execute_io(
&self,
command: &str,
stdout_channel: Sender<Vec<u8>>,
stderr_channel: Option<Sender<Vec<u8>>>,
stdin_channel: Option<Receiver<Vec<u8>>>,
request_pty: bool,
default_exit_code: Option<u32>,
) -> Result<u32, Error>
pub async fn execute_io( &self, command: &str, stdout_channel: Sender<Vec<u8>>, stderr_channel: Option<Sender<Vec<u8>>>, stdin_channel: Option<Receiver<Vec<u8>>>, request_pty: bool, default_exit_code: Option<u32>, ) -> Result<u32, Error>
Execute a remote command via the ssh connection and perform i/o via channels.
execute_io does the same as execute, but ties stdin and stdout/stderr to channels.
Giving a stdin channel is optional. If there is only a stdout channel, stderr will be
sent to the stdout channel. Sending an empty string to the stdin channel will send an
EOF to the remote side.
If request_pty is true, a pseudo terminal is requested for the session. This is
sometime necessary for example to enter a password, which is not request via stdin
but directly from the terminal. NOTE: A pty has no stderr, so stderr output is
sent to the stdout channel.
The exit code of the command is returned as a result. If the remote ssh server
does not report an exit code, a default exit code can be passed, otherwise an error
is returned.
Example:
use async_ssh2_tokio::{Client, AuthMethod, ServerCheckMethod};
use tokio::sync::mpsc;
#[tokio::main]
async fn main() -> Result<(), async_ssh2_tokio::Error> {
let mut client = Client::connect(
("10.10.10.2", 22),
"root",
AuthMethod::with_password("root"),
ServerCheckMethod::NoCheck,
).await?;
let mut result_stdout = vec![];
let mut result_stderr = vec![];
let (stdout_tx, mut stdout_rx) = mpsc::channel(10);
let (stderr_tx, mut stderr_rx) = mpsc::channel(10);
let cmd = "date";
let exec_future = client.execute_io(&cmd, stdout_tx, Some(stderr_tx), None, false, None);
tokio::pin!(exec_future);
let result = loop {
tokio::select! {
result = &mut exec_future => break result,
Some(stdout) = stdout_rx.recv() => {
println!("ssh stdout: {}", String::from_utf8_lossy(&stdout));
result_stdout.push(stdout);
},
Some(stderr) = stderr_rx.recv() => {
println!("ssh stderr: {}", String::from_utf8_lossy(&stderr));
result_stderr.push(stderr);
},
};
}?;
// see if any output is left in the channels
if let Some(stdout) = stdout_rx.recv().await {
println!("ssh stdout: {}", String::from_utf8_lossy(&stdout));
result_stdout.push(stdout);
}
if let Some(stderr) = stderr_rx.recv().await {
println!("ssh stderr: {}", String::from_utf8_lossy(&stderr));
result_stderr.push(stderr);
}
Ok(())
}Sourcepub fn get_connection_username(&self) -> &String
pub fn get_connection_username(&self) -> &String
A debugging function to get the username this client is connected as.
Sourcepub fn get_connection_address(&self) -> &SocketAddr
pub fn get_connection_address(&self) -> &SocketAddr
A debugging function to get the address this client is connected to.