Skip to main content
Reach a running sandbox over SSH: open a native in-process SSH client, run exec requests, attach an interactive shell, transfer files over SFTP, or stand up a reusable SSH server endpoint. Requires the ssh feature. See SSH for usage flows.
microsandbox = { version = "0.5.8", features = ["ssh"] }

Typical flow

use microsandbox::Sandbox;

let sb = Sandbox::builder("api")
    .image("python")
    .create()
    .await?;

let client = sb.ssh().connect().await?;      // 1. open an SSH client
let out = client.exec("python -V").await?;   // 2. run a command
println!("{}", String::from_utf8_lossy(&out.stdout));

client.close().await?;                       // 3. close the session

Sandbox

sb.ssh()

fn ssh(&self) -> SandboxSshOps
let client = sb.ssh().connect().await?;
Return the SSH namespace for this sandbox. The namespace holds the SSH client and server helpers; nothing connects until you call connect or server.

Returns

SSH namespace for this sandbox.

SandboxSshOps

SSH namespace for a sandbox, obtained from sb.ssh(). SSH is only supported on local sandboxes; calls error with Unsupported against a cloud backend.

ssh.connect()

async fn connect(&self) -> MicrosandboxResult<SshClient>
let client = sb.ssh().connect().await?;
let out = client.exec("uname -a").await?;
Connect a native in-process SSH client to this sandbox. Generates an ephemeral Ed25519 client and host key pair, stands up an internal server bound to a duplex stream, and authenticates over public key. Uses default client options (user root, terminal from $TERM, SFTP enabled).

Returns

Connected SSH client session.

ssh.open_client()

async fn open_client(&self) -> MicrosandboxResult<SshClient>
Alias for connect.

Returns

Connected SSH client session.

ssh.connect_with()

async fn connect_with(
    &self,
    f: impl FnOnce(SshClientOptionsBuilder) -> SshClientOptionsBuilder,
) -> MicrosandboxResult<SshClient>
let client = sb.ssh().connect_with(|opts| opts
    .user("app")
    .term("xterm-256color")).await?;
Connect a native in-process SSH client with custom options. The closure configures the login user, terminal name, and whether SFTP is enabled on the internal server.

Parameters

Configure user, terminal, and SFTP support.

Returns

Connected SSH client session.

ssh.open_client_with()

async fn open_client_with(
    &self,
    f: impl FnOnce(SshClientOptionsBuilder) -> SshClientOptionsBuilder,
) -> MicrosandboxResult<SshClient>
Alias for connect_with.

Parameters

Configure user, terminal, and SFTP support.

Returns

Connected SSH client session.

ssh.server()

async fn server(&self) -> MicrosandboxResult<SshServer>
let server = sb.ssh().server().await?;
let (client_io, server_io) = tokio::io::duplex(64 * 1024);
server.serve(server_io).await?;
Prepare a reusable SSH server endpoint for this sandbox. Loads or creates the host key and resolves authorized keys from the default authorized-keys file. The returned SshServer is cloneable and can serve many connections.

Returns

Reusable SSH server endpoint.

ssh.prepare_server()

async fn prepare_server(&self) -> MicrosandboxResult<SshServer>
Alias for server.

Returns

Reusable SSH server endpoint.

ssh.server_with()

async fn server_with(
    &self,
    f: impl FnOnce(SshServerOptionsBuilder) -> SshServerOptionsBuilder,
) -> MicrosandboxResult<SshServer>
let server = sb.ssh().server_with(|opts| opts
    .authorized_key("ssh-ed25519 AAAAC3Nza...")
    .user("app")
    .sftp(false)).await?;
Prepare a server endpoint with custom host-key, authorization, guest-user, or SFTP options. If no authorized keys are configured, the default authorized-keys file is loaded; an empty key set is an error.

Parameters

Configure host key, authorized keys, guest user, and SFTP.

Returns

Reusable SSH server endpoint.

ssh.prepare_server_with()

async fn prepare_server_with(
    &self,
    f: impl FnOnce(SshServerOptionsBuilder) -> SshServerOptionsBuilder,
) -> MicrosandboxResult<SshServer>
Alias for server_with.

Parameters

Configure host key, authorized keys, guest user, and SFTP.

Returns

Reusable SSH server endpoint.

SshClient

A connected, native in-process SSH client session, obtained from connect or connect_with. Aborts its internal server task on drop.

client.exec()

async fn exec(&self, command: impl Into<String>) -> MicrosandboxResult<SshOutput>
let out = client.exec("echo hello").await?;
println!("exit {}: {}", out.status, String::from_utf8_lossy(&out.stdout));
Run an SSH exec request and collect stdout, stderr, and the exit status. The command is run through the sandbox’s configured shell (default /bin/sh -c). No PTY is requested.

Parameters

commandimpl Into<String>
Command string sent through SSH.

Returns

Captured output and exit status.

client.exec_with()

async fn exec_with(
    &self,
    command: impl Into<String>,
    f: impl FnOnce(SshExecOptionsBuilder) -> SshExecOptionsBuilder,
) -> MicrosandboxResult<SshOutput>
let out = client.exec_with("top -bn1", |opts| opts.tty(true)).await?;
Run an SSH exec request with options. The closure can request a PTY via tty; when a PTY is allocated, stderr is folded into stdout.

Parameters

commandimpl Into<String>
Command string sent through SSH.
Configure exec options.

Returns

Captured output and exit status.

client.attach()

async fn attach(&self) -> MicrosandboxResult<i32>
let code = client.attach().await?;
println!("shell exited with {code}");
Attach the local terminal to an interactive SSH shell. Requests a PTY sized to the current terminal, puts the terminal into raw mode, forwards keystrokes, relays window-resize events, and returns when the shell exits or the default detach key sequence is typed.

Returns

i32
Shell exit code (128 if terminated by signal).

client.attach_with()

async fn attach_with(
    &self,
    f: impl FnOnce(SshAttachOptionsBuilder) -> SshAttachOptionsBuilder,
) -> MicrosandboxResult<i32>
let code = client.attach_with(|opts| opts
    .term("xterm-256color")
    .detach_keys("ctrl-p,ctrl-q")).await?;
Attach an interactive shell with custom terminal and detach-key options.

Parameters

Configure terminal name and detach keys.

Returns

i32
Shell exit code (128 if terminated by signal).

client.sftp()

async fn sftp(&self) -> MicrosandboxResult<SftpClient>
let sftp = client.sftp().await?;
let mut file = sftp.create("/tmp/hello.txt").await?;
Open an SFTP client session over this SSH connection. Requests the sftp subsystem and returns a high-level SFTP session for reading, writing, and listing files inside the guest.

Returns

SFTP client session.

client.close()

async fn close(self) -> MicrosandboxResult<()>
client.close().await?;
Close this native SSH client session. Sends a disconnect and aborts the internal server task. Consumes the client.

SshServer

A reusable SSH server endpoint for a sandbox, obtained from server or server_with. Cloneable; each call to serve handles one connection.

server.serve()

async fn serve<S>(&self, stream: S) -> MicrosandboxResult<()>
where
    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
let server = sb.ssh().server().await?;
let (client_io, server_io) = tokio::io::duplex(64 * 1024);
tokio::spawn(async move { server.serve(server_io).await });
Serve one SSH connection over an ordered duplex stream. Runs the SSH handshake and session loop to completion. Returns when the connection closes.

Parameters

streamS: AsyncRead + AsyncWrite
Ordered duplex SSH transport.

server.serve_connection()

async fn serve_connection<S>(&self, stream: S) -> MicrosandboxResult<()>
where
    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
Alias for serve.

Parameters

streamS: AsyncRead + AsyncWrite
Ordered duplex SSH transport.

SshStdioStream

SshStdioStream::new()

fn new() -> Self
use microsandbox::SshStdioStream;

let server = sb.ssh().server().await?;
server.serve(SshStdioStream::new()).await?;
Create a stdio SSH transport stream backed by this process’s stdin and stdout. Implements AsyncRead and AsyncWrite, so it can be passed straight to serve to bridge an SSH connection over the parent process’s standard streams. Also available via Default.

Returns

Duplex stream over stdin/stdout.

Constants

DEFAULT_SSH_HOST

pub const DEFAULT_SSH_HOST: &str = "127.0.0.1";
Default SSH listener host used by the CLI adapter when binding a sandbox SSH endpoint.

DEFAULT_SSH_PORT

pub const DEFAULT_SSH_PORT: u16 = 2222;
Default SSH listener port used by the CLI adapter when binding a sandbox SSH endpoint.

Types

SshOutput

Returned by client.exec(), client.exec_with()

Output from an SSH exec request.
FieldTypeDescription
statusi32Exit status code.
stdoutBytesCaptured stdout bytes.
stderrBytesCaptured stderr bytes (folded into stdout when a PTY is allocated).

SandboxSshOps

Returned by sb.ssh()

SSH namespace for a sandbox. Cheap to clone; holds a clone of the sandbox.
MethodReturnsDescription
connect()SshClientOpen a client with defaults.
open_client()SshClientAlias of connect().
connect_with()SshClientOpen a client with options.
open_client_with()SshClientAlias of connect_with().
server()SshServerPrepare a server endpoint.
prepare_server()SshServerAlias of server().
server_with()SshServerServer endpoint with options.
prepare_server_with()SshServerAlias of server_with().

SshClient

Returned by ssh.connect(), ssh.connect_with()

Native in-process SSH client session. Aborts its internal server task on drop.
MethodReturnsDescription
exec()SshOutputRun a command.
exec_with()SshOutputRun with options.
attach()i32Interactive shell.
attach_with()i32Attach with options.
sftp()SftpClientOpen an SFTP session.
close()()Close the session.

SshServer

Returned by ssh.server(), ssh.server_with()

Reusable SSH server endpoint for a sandbox. Cloneable.
MethodReturnsDescription
serve()()Serve one connection.
serve_connection()()Alias of serve().

SftpClient

Returned by client.sftp()

High-level SFTP client session.
pub type SftpClient = russh_sftp::client::SftpSession;

SshStdioStream

Used by server.serve()

Ordered duplex stream backed by this process’s stdin and stdout. Implements AsyncRead and AsyncWrite.
MethodReturnsDescription
new()SshStdioStreamCreate a stdio transport stream.

SshClientOptionsBuilder

Used by ssh.connect_with()

Builder for SSH client options. Defaults: user root, terminal from $TERM (falling back to xterm), SFTP enabled.
MethodParametersDescription
user()impl Into<String>SSH login user. Default root.
term()impl Into<String>Terminal name for interactive sessions.
sftp()boolEnable or disable SFTP on the internal server. Default true.
build()Finalize the options.

SshExecOptionsBuilder

Used by client.exec_with()

Builder for SSH exec options.
MethodParametersDescription
tty()boolRequest a PTY for the exec channel. Default false.
build()Finalize the options.

SshAttachOptionsBuilder

Used by client.attach_with()

Builder for interactive SSH attach options. Default terminal comes from $TERM (falling back to xterm); detach keys default to the standard sequence.
MethodParametersDescription
term()impl Into<String>Terminal name for the shell.
detach_keys()impl Into<String>Detach key sequence.
build()Finalize the options.

SshServerOptionsBuilder

Used by ssh.server_with()

Builder for SSH server options. SFTP is enabled by default; when no authorized keys are provided, the default authorized-keys file is loaded.
MethodParametersDescription
host_key_path()impl Into<PathBuf>Override the host private key path.
host_key()PrivateKeyUse an in-memory host private key.
authorized_keys_path()impl Into<PathBuf>Override the authorized-keys path.
authorized_key()impl Into<String>Add one in-memory authorized public key.
user()impl Into<String>Override the guest user used for exec requests.
sftp()boolEnable or disable SFTP. Default true.
build()Finalize the options.