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. See SSH for usage flows.

Typical flow

import (
    "context"

    m "github.com/superradcompany/microsandbox/sdk/go"
)

ctx := context.Background()

client, err := sb.SSH().OpenClient(ctx)   // 1. open a native client
if err != nil {
    return err
}
defer client.Close(ctx)

out, err := client.Exec(ctx, "uname -a")  // 2. run a command
if err != nil {
    return err
}
fmt.Printf("%s (exit %d)\n", out.Stdout, out.Status)

Methods

sb.SSH()

func (s *Sandbox) SSH() *SandboxSSHOps
ssh := sb.SSH()
client, err := ssh.OpenClient(ctx)
Return the SSH operations namespace for this sandbox. The namespace groups the client and server helpers; it holds no resources of its own.

Returns

SSH client and server helpers for this sandbox.

ssh.OpenClient()

func (ssh *SandboxSSHOps) OpenClient(ctx context.Context, opts ...SSHClientOption) (*SSHClient, error)
client, err := sb.SSH().OpenClient(ctx,
    m.WithSSHUser("app"),
    m.WithSSHTerm("xterm-256color"),
)
if err != nil {
    return err
}
defer client.Close(ctx)
Open 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. With no options it uses login user root, terminal from $TERM (falling back to xterm), and SFTP enabled.

Parameters

ctxcontext.Context
Cancels the connection attempt.
Login user, terminal name, and SFTP toggle.

Returns

Native SSH client session.
error
Typed microsandbox error.

ssh.PrepareServer()

func (ssh *SandboxSSHOps) PrepareServer(ctx context.Context, opts ...SSHServerOption) (*SSHServer, error)
srv, err := sb.SSH().PrepareServer(ctx,
    m.WithSSHAuthorizedKeysPath("/etc/msb/authorized_keys"),
)
if err != nil {
    return err
}
defer srv.Close(ctx)
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 unless overridden. The returned SSHServer can serve connections one at a time over the process’s standard streams.

Parameters

ctxcontext.Context
Cancels server preparation.
Host key, authorized keys, guest user, and SFTP toggle.

Returns

Prepared server endpoint.
error
Typed microsandbox error.

c.Exec()

func (c *SSHClient) Exec(ctx context.Context, command string, opts ...SSHExecOption) (*SSHOutput, error)
out, err := client.Exec(ctx, "python -V")
if err != nil {
    return err
}
if !out.Success() {
    return fmt.Errorf("exit %d: %s", out.Status, out.Stderr)
}
fmt.Printf("%s", 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. No PTY is requested unless WithSSHTTY is passed.

Parameters

ctxcontext.Context
Cancels the exec request.
commandstring
Command string sent through SSH.
PTY toggle for the exec channel.

Returns

Captured stdout, stderr, and exit status.
error
Typed microsandbox error.

c.Attach()

func (c *SSHClient) Attach(ctx context.Context, opts ...SSHAttachOption) (int, error)
code, err := client.Attach(ctx,
    m.WithSSHAttachTerm("xterm-256color"),
    m.WithSSHDetachKeys("ctrl-p,ctrl-q"),
)
if err != nil {
    return err
}
fmt.Printf("shell exited with %d\n", code)
Bridge 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 detach key sequence is typed.

Parameters

ctxcontext.Context
Cancels the attach session.
Terminal name and detach key sequence.

Returns

int
Shell exit code (128 if terminated by signal).
error
Typed microsandbox error.

c.SFTP()

func (c *SSHClient) SFTP(ctx context.Context) (*SFTPClient, error)
sftp, err := client.SFTP(ctx)
if err != nil {
    return err
}
defer sftp.Close(ctx)

if err := sftp.Write(ctx, "/tmp/hello.txt", []byte("hi")); err != nil {
    return err
}
Open an SFTP session over this SSH connection. Returns a high-level SFTP client for reading, writing, and managing files inside the guest. Requires SFTP enabled on the client (the default).

Parameters

ctxcontext.Context
Cancels opening the SFTP session.

Returns

SFTP client session.
error
Typed microsandbox error.

c.Close()

func (c *SSHClient) Close(ctx context.Context) error
defer client.Close(ctx)
Close this SSH client session. The handle is consumed; do not use it after closing.

Parameters

ctxcontext.Context
Cancels the close.

Returns

error
Typed microsandbox error.

srv.ServeConnection()

func (srv *SSHServer) ServeConnection(ctx context.Context) error
srv, err := sb.SSH().PrepareServer(ctx)
if err != nil {
    return err
}
defer srv.Close(ctx)

if err := srv.ServeConnection(ctx); err != nil {
    return err
}
Serve one SSH transport over this process’s stdin and stdout. Returns when the connection ends. Call again on the same SSHServer to serve another connection.

Parameters

ctxcontext.Context
Cancels serving the connection.

Returns

error
Typed microsandbox error.

srv.Close()

func (srv *SSHServer) Close(ctx context.Context) error
defer srv.Close(ctx)
Release this prepared server endpoint. The handle is consumed; do not use it after closing.

Parameters

ctxcontext.Context
Cancels the close.

Returns

error
Typed microsandbox error.

o.Success()

func (o SSHOutput) Success() bool
out, err := client.Exec(ctx, "test -f /etc/passwd")
if err != nil {
    return err
}
fmt.Println("present:", out.Success())
Report whether the command exited with status 0.

Returns

bool
true when Status is 0.

Types

SandboxSSHOps

Returned by SSH()

SSH operations namespace for a sandbox. Obtained via sb.SSH(). Holds no resources; it groups the client and server entry points.
MethodReturnsDescription
OpenClient(ctx, opts...)(*SSHClient, error)Open a native in-process SSH client
PrepareServer(ctx, opts...)(*SSHServer, error)Prepare a reusable SSH server endpoint

SSHClient

Returned by OpenClient()

A native in-process SSH client session. Obtained via OpenClient().
MethodReturnsDescription
Exec(ctx, command, opts...)(*SSHOutput, error)Run a command and collect output
Attach(ctx, opts...)(int, error)Bridge the local terminal to an interactive shell
SFTP(ctx)(*SFTPClient, error)Open an SFTP session over this connection
Close(ctx)errorClose the session (consumes the handle)

SFTPClient

Returned by SFTP()

A high-level SFTP client session over an SSH connection. Obtained via SFTP().
MethodReturnsDescription
Read(ctx, path)([]byte, error)Read a file into memory
Write(ctx, path, data)errorWrite a file, creating or truncating it
Mkdir(ctx, path)errorCreate a directory
RemoveFile(ctx, path)errorRemove a file
RemoveDir(ctx, path)errorRemove an empty directory
Rename(ctx, oldPath, newPath)errorRename a file or directory
RealPath(ctx, path)(string, error)Resolve a path to its canonical absolute form
ReadLink(ctx, path)(string, error)Read a symlink target
Symlink(ctx, target, linkPath)errorCreate a symlink
Close(ctx)errorClose the session (consumes the handle)

SSHServer

Returned by PrepareServer()

A prepared SSH server endpoint for a sandbox. Obtained via PrepareServer().
MethodReturnsDescription
ServeConnection(ctx)errorServe one SSH transport over stdin/stdout
Close(ctx)errorRelease the endpoint (consumes the handle)

SSHOutput

Returned by Exec()

The output from an SSH exec request.
Field / MethodTypeDescription
StatusintExit status code
Stdout[]byteCaptured stdout bytes
Stderr[]byteCaptured stderr bytes
Success()booltrue when Status is 0

SSHClientOption

Used by OpenClient()

Functional option for OpenClient(). Defaults: user root, terminal from $TERM (falling back to xterm), SFTP enabled.
OptionDescription
WithSSHUser(user)SSH login user. Default root
WithSSHTerm(term)Terminal name for interactive sessions
WithSSHClientSFTP(enabled)Enable or disable SFTP on the internal server. Default true

SSHExecOption

Used by Exec()

Functional option for Exec().
OptionDescription
WithSSHTTY(enabled)Request a PTY for the exec channel

SSHAttachOption

Used by Attach()

Functional option for Attach(). The default terminal comes from $TERM (falling back to xterm); detach keys default to the standard sequence.
OptionDescription
WithSSHAttachTerm(term)Terminal name for the interactive shell
WithSSHDetachKeys(keys)Detach key sequence

SSHServerOption

Used by PrepareServer()

Functional option for PrepareServer(). SFTP is enabled by default; when no authorized-keys path is provided, the default authorized-keys file is loaded.
OptionDescription
WithSSHHostKeyPath(path)Override the host private key path
WithSSHAuthorizedKeysPath(path)Override the authorized-keys path
WithSSHServerUser(user)Override the guest user used for SSH exec requests
WithSSHServerSFTP(enabled)Enable or disable SFTP on the server endpoint. Default true