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 server endpoint that serves connections over stdin/stdout. See SSH for usage flows.

Typical flow

from microsandbox import Sandbox

async with await Sandbox.create("api", image="python") as sb:
    client = await sb.ssh().open_client()       # 1. open an SSH client
    out = await client.exec("python -V")        # 2. run a command
    print(out.stdout_text)

    await client.close()                        # 3. close the session

Sandbox

sb.ssh()

def ssh() -> SandboxSshOps
client = await sb.ssh().open_client()
Return the SSH namespace for this sandbox. The namespace holds the SSH client and server helpers; nothing connects until you call open_client() or prepare_server(). This method is synchronous; the helpers it returns are async.

Returns

SSH namespace for this sandbox.

SandboxSshOps

SSH namespace for a sandbox, obtained from sb.ssh(). SSH is only supported on local sandboxes.

ssh.open_client()

async def open_client(
    *,
    user: str = "root",
    term: str | None = None,
    sftp: bool = True,
) -> SshClient
client = await sb.ssh().open_client(user="app", term="xterm-256color")
out = await client.exec("uname -a")
Connect a native in-process SSH client to this sandbox. Generates an ephemeral client and host key pair, stands up an internal server bound to an in-memory stream, and authenticates over public key.

Parameters

userstr
SSH login user. Default “root”.
termstr | None
Terminal name for interactive sessions. Defaults to $TERM.
sftpbool
Enable or disable SFTP on the internal server. Default True.

Returns

Connected SSH client session.

ssh.prepare_server()

async def prepare_server(
    *,
    host_key_path: str | os.PathLike[str] | None = None,
    authorized_keys_path: str | os.PathLike[str] | None = None,
    user: str | None = None,
    sftp: bool = True,
) -> SshServer
server = await sb.ssh().prepare_server(
    authorized_keys_path="/home/me/.ssh/authorized_keys",
    user="app",
    sftp=False,
)
await server.serve_connection()
Prepare a reusable SSH server endpoint for this sandbox. Loads or creates the host key and resolves authorized keys, falling back to the default authorized-keys file when no path is given. The returned SshServer serves one connection over this process’s stdin/stdout.

Parameters

host_key_pathstr | os.PathLike[str] | None
Override the host private key path.
authorized_keys_pathstr | os.PathLike[str] | None
Override the authorized-keys path.
userstr | None
Override the guest user used for exec requests.
sftpbool
Enable or disable SFTP. Default True.

Returns

Reusable SSH server endpoint.

SshClient

A connected, native in-process SSH client session, obtained from ssh.open_client().

client.exec()

async def exec(command: str, *, tty: bool = False) -> SshOutput
out = await client.exec("echo hello")
print(f"exit {out.status}: {out.stdout_text}")
Run an SSH exec request and collect stdout, stderr, and the exit status. The command runs through the sandbox’s configured shell. When tty=True a PTY is allocated and stderr is folded into stdout.

Parameters

commandstr
Command string sent through SSH.
ttybool
Request a PTY for the exec channel. Default False.

Returns

Captured output and exit status.

client.attach()

async def attach(
    *,
    term: str | None = None,
    detach_keys: str | None = None,
) -> int
code = await client.attach(term="xterm-256color", detach_keys="ctrl-p,ctrl-q")
print(f"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, and returns when the shell exits or the detach key sequence is typed.

Parameters

termstr | None
Terminal name for the shell. Defaults to $TERM.
detach_keysstr | None
Detach key sequence, e.g. “ctrl-p,ctrl-q”.

Returns

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

client.sftp()

async def sftp() -> SftpClient
sftp = await client.sftp()
await sftp.write("/tmp/hello.txt", b"hi")
data = await sftp.read("/tmp/hello.txt")
Open an SFTP client session over this SSH connection. Requests the sftp subsystem and returns a high-level session for reading, writing, and listing files inside the guest.

Returns

SFTP client session.

client.close()

async def close() -> None
await client.close()
Close this native SSH client session. Sends a disconnect and aborts the internal server task.

SshServer

A reusable SSH server endpoint for a sandbox, obtained from ssh.prepare_server().

server.serve_connection()

async def serve_connection() -> None
server = await sb.ssh().prepare_server()
await server.serve_connection()
Serve one SSH transport over this process’s stdin/stdout. Runs the SSH handshake and session loop to completion, returning when the connection closes. Use this to bridge an SSH connection over the parent process’s standard streams.

server.close()

def close() -> None
server.close()
Release this prepared server endpoint. This method is synchronous.

Types

SandboxSshOps

Returned by sb.ssh()

SSH namespace for a sandbox.
MethodReturnsDescription
open_client()SshClient(async) Open a client.
prepare_server()SshServer(async) Prepare a server endpoint.

SshClient

Returned by ssh.open_client()

Native in-process SSH client session.
MethodReturnsDescription
exec(command, *, tty=False)SshOutput(async) Run a command.
attach(*, term=None, detach_keys=None)int(async) Interactive shell.
sftp()SftpClient(async) Open an SFTP session.
close()None(async) Close the session.

SshServer

Returned by ssh.prepare_server()

Reusable SSH server endpoint for a sandbox.
MethodReturnsDescription
serve_connection()None(async) Serve one connection over stdin/stdout.
close()NoneRelease the prepared endpoint.

SftpClient

Returned by client.sftp()

High-level SFTP client session over an SSH connection. All methods are async.
MethodReturnsDescription
read(path)bytesRead a file into memory.
write(path, data)NoneWrite a file, creating or truncating it.
mkdir(path)NoneCreate a directory.
remove_file(path)NoneRemove a file.
remove_dir(path)NoneRemove an empty directory.
rename(old_path, new_path)NoneRename a file or directory.
real_path(path)strResolve a path to its canonical absolute form.
read_link(path)strRead a symlink target.
symlink(target, link_path)NoneCreate a symlink.
close()NoneClose the SFTP session.

SshOutput

Returned by client.exec()

Output from an SSH exec request.
PropertyTypeDescription
statusintExit status code.
successboolWhether the command exited successfully.
stdout_textstrStdout as UTF-8 text.
stderr_textstrStderr as UTF-8 text.
stdout_bytesbytesStdout as raw bytes.
stderr_bytesbytesStderr as raw bytes.