Skip to main content

Overview

The SmolVM class provides a user-friendly interface for creating and managing microVMs. It supports automatic configuration, context manager usage, and command execution over the selected control channel.

Constructor

config
VMConfig | None
default:"None"
VM configuration. Mutually exclusive with vm_id. If omitted (and vm_id is omitted), SmolVM auto-creates a default configuration that can run commands over vsock or SSH.
vm_id
str | None
default:"None"
ID of an existing VM to reconnect to. Mutually exclusive with config.
image
str | None
default:"None"
Disk image to boot. Accepts:
  • A published S3 image URI (s3://bucket/images/alpine/) — the manifest defines the OS, so os= must be omitted.
  • A local qcow2 file path (/var/lib/vms/win11.qcow2, ~/win11/disk.qcow2) or file:// URI — requires os= since the file alone doesn’t self-identify.
Mutually exclusive with config and vm_id. Local images are only supported for os="windows" in this release; see Windows guests.
os
GuestOS | str | None
default:"None"
Guest operating system. Valid values: "alpine", "ubuntu", "windows".
  • For auto-config mode (no image=), selects the Linux distribution.
  • For local images, required — tells SmolVM which OS is inside the file. Must be "windows" for the local-image path in this release.
  • For S3 images, must be omitted — the image manifest already records the OS.
data_dir
Path | None
default:"None"
Override the default data directory for VM state storage.
socket_dir
Path | None
default:"None"
Override the default socket directory.
backend
str | None
default:"None"
Runtime backend override. Options: "firecracker", "qemu", or "auto".
memory
int | None
default:"None"
Guest memory in MiB for auto-config mode (when both config and vm_id are omitted). Default is 512 MiB.
disk_size
int | None
default:"None"
Root filesystem size in MiB for auto-config mode. Default is 512 MiB. Minimum is 64 MiB.
ssh_user
str
default:"root"
SSH user for command execution via the run() method. For Windows guests, pass the local Windows account name (for example "Administrator") — root does not exist on Windows OpenSSH.
ssh_key_path
str | None
default:"None"
SSH private key path. If omitted, SmolVM first tries default SSH auth, then falls back to ~/.smolvm/keys/id_ed25519.
ssh_password
str | None
default:"None"
SSH password. Use this when the guest only accepts password authentication — common for Windows qcow2s that ship with OpenSSH Server but no preinstalled key. When set, SmolVM skips key-based auth so paramiko does not silently prefer a key over your password.
comm_channel
Literal["ssh", "vsock"] | None
default:"None"
Host-to-guest control channel for run(), file transfer, and env var operations. Leave unset for auto-selection (vsock when the SmolVM guest agent answers on a Linux QEMU host, otherwise SSH). Pass "vsock" to require vsock — SmolVM raises if the agent does not answer instead of falling back. Pass "ssh" to force the SSH path. See control channel for details.
callbacks
list[Callback] | None
default:"None"
Callbacks that fire around each run() call. Use them to inspect, log, or block commands before they reach the guest. See Run callbacks and safety hooks for the full guide and the Callback reference.

Raises

  • ValueError: If both config and vm_id are provided, or if memory/disk_size are set outside auto-config mode.

Class Methods

from_id

Reconnect to an existing VM by ID. Pass ssh_password= for Windows guests that use password-based SSH. Pass comm_channel= to override the host-to-guest control channel — see control channel.
vm_id
str
required
VM identifier to reconnect to.
return
SmolVM
A SmolVM instance bound to the existing VM.

Raises

  • VMNotFoundError: If no VM with this ID exists.

from_image

Launch a VM from a custom BootImage without writing a VMConfig by hand. The image supplies the rootfs, kernel, and boot arguments; from_image resolves the backend, architecture, and any missing base kernel, then applies the per-VM runtime knobs you pass in. Use this when you have built a custom image (for example with DockerRootfsBuilder) and want a one-line launcher that still lets you tune memory, networking, port forwards, vsock, and the host-to-guest control channel.
image
BootImage
required
Image to boot. Direct-kernel images may omit kernel_path — SmolVM downloads the matching base kernel automatically. Custom images without an SSH server can still boot, but command helpers such as vm.run(...) require an SSH-capable image or guest agent.
vm_id
str | None
default:"None"
Custom VM identifier. Defaults to an auto-generated name using name_prefix.
name_prefix
str
default:"sbx"
Prefix used when SmolVM generates a vm_id.
backend
str | None
default:"None"
Runtime backend ("firecracker", "qemu", or "libkrun"). Defaults to the backend recorded on the image, otherwise normal auto-selection. Firmware-boot images require "qemu".SmolVM’s public guides focus on Firecracker and QEMU because they have the broadest current support.
arch
str | None
default:"None"
Guest architecture ("amd64" or "arm64"). Defaults to the image’s recorded arch, otherwise the host arch.
vcpus
int
default:"1"
Number of guest vCPUs.
memory_mb
int
default:"512"
Guest memory in MiB.
guest_os
GuestOS | str
default:"GuestOS.ALPINE"
Guest OS hint used by SmolVM’s lifecycle helpers ("alpine", "ubuntu", or "windows").
network
Literal["tap", "slirp"] | None
default:"None"
QEMU network mode. Use "slirp" to enable user-mode networking with port_forwards. Ignored for non-QEMU backends.
port_forwards
list[PortForwardConfig | dict] | None
default:"None"
Host-to-guest port forwards. Only valid with backend="qemu" and network="slirp".
vsock
VsockConfig | dict | None
default:"None"
Vsock configuration for host-to-guest control or custom services.
comm_channel
Literal["ssh", "vsock"] | None
default:"None"
Host-to-guest control channel for run() and file transfers. See control channel.
disk_mode
Literal["isolated", "shared"]
default:"isolated"
Whether each VM gets its own per-VM disk overlay ("isolated") or shares the base image ("shared").
disk_size_mb
int | None
default:"None"
Target size in MiB for the per-VM disk. SmolVM only grows the disk — pick a value at least as large as the image’s current size. Requires disk_mode="isolated" (the default); shared base images are never resized. Works for both raw-ext4 and qcow2 rootfs formats.
grow_filesystem
bool
default:"False"
After resizing the disk, grow the guest filesystem to fill it. Only supported for raw-ext4 rootfs images and requires e2fsprogs (e2fsck, resize2fs) on the host. Leave False for qcow2 images and grow the filesystem from inside the guest instead.
ssh_user
str
default:"root"
SSH user for run(). Ignored when the image is not SSH-capable.
ssh_key_path
str | None
default:"None"
SSH private key path.
ssh_password
str | None
default:"None"
SSH password. Use this for images that ship password-only SSH.
return
SmolVM
A SmolVM instance bound to the new VM. Call start() (or use the context manager) to boot it.

Raises

  • ValueError: If the requested backend, arch, network mode, or port_forwards are incompatible with the image (for example, port_forwards outside QEMU slirp, or a firmware image on Firecracker).
  • SmolVMError: If a disk resize is requested but cannot be honored — for example, disk_mode="shared", grow_filesystem=True on a qcow2 image, a disk_size_mb smaller than the current disk, or e2fsprogs missing on the host.

Example

browser

Start a Chromium browser inside a disposable sandbox. Use headless=True for a Chrome DevTools Protocol automation URL, or headless=False to also get a live viewer and VNC display URL. VNC means Virtual Network Computing, a standard way to view and control a remote screen.
return
DisplaySandboxProtocol
A started browser sandbox with cdp_url, and with viewer_url plus display_url when headless=False.
See Browser and desktop sandboxes for the full option list and examples.

desktop

Start a full desktop display inside a disposable sandbox. Use viewer_url to open the desktop in your browser, or display_url for a VNC-compatible computer-use agent.
return
DisplaySandboxProtocol
A started desktop sandbox with viewer_url and display_url.
See Browser and desktop sandboxes for desktop examples.

from_snapshot

Restore a snapshot and attach a facade to the restored VM.
snapshot_id
str
required
The identifier of the snapshot to restore.
resume_vm
bool
default:"False"
Resume the restored VM immediately. When False, the VM is restored in a paused state.
force
bool
default:"False"
Allow restoring a snapshot that was already restored before. By default, each snapshot can only be restored once.
data_dir
Path | None
default:"None"
Override the default data directory.
socket_dir
Path | None
default:"None"
Override the default socket directory.
backend
str | None
default:"None"
Runtime backend override.
ssh_user
str
default:"root"
SSH user for command execution.
ssh_key_path
str | None
default:"None"
SSH private key path.
return
SmolVM
A SmolVM instance bound to the restored VM.

Raises

  • SnapshotNotFoundError: If no snapshot with this ID exists.
  • SmolVMError: If the snapshot was already restored (use force=True to override).

Lifecycle Methods

start

Start the VM. If the VM config contains env_vars, they are injected into the guest via SSH after boot completes.
boot_timeout
float
default:"30.0"
Maximum seconds to wait for boot to complete.
return
SmolVM
Returns self for method chaining.

Raises

  • SmolVMError: If env_vars is set but the image does not support SSH (missing init=/init in boot args).

stop

Stop the VM gracefully.
timeout
float
default:"3.0"
Seconds to wait for graceful shutdown.
return
SmolVM
Returns self for method chaining.

delete

Delete the VM and release all resources.

pause

Pause a running VM. The VM’s memory and CPU state are frozen in place. Use resume() to continue execution.
return
SmolVM
Returns self for method chaining.

Raises

  • SmolVMError: If the VM is not in a pausable state (must be running).

resume

Resume a paused VM. Execution continues from the exact point where it was paused.
return
SmolVM
Returns self for method chaining.

Raises

  • SmolVMError: If the VM is not paused.

snapshot

Create a snapshot of the VM. The VM must be running or paused. If running, SmolVM pauses it during snapshot creation unless resume_source=True is set.
snapshot_id
str | None
default:"None"
Custom snapshot identifier. If omitted, SmolVM generates one automatically (for example, snap-my-vm-1717012345). Must contain only lowercase letters, numbers, hyphens, and underscores.
snapshot_type
SnapshotType | str
default:"SnapshotType.FULL"
What to save:
  • "full" — complete disk copy plus memory and CPU state.
  • "diff" — smaller disk artifact. QEMU diff snapshots need their backing image at restore time.
  • "disk" — disk-only on QEMU; restores as a cold boot.
On Firecracker, SmolVM captures memory and VM state for every snapshot type.
resume_source
bool
default:"False"
Resume the source VM after snapshot creation. When False, the VM stays paused.
return
SnapshotInfo
Metadata about the created snapshot, including file paths and timestamps.

Raises

  • SnapshotAlreadyExistsError: If a snapshot with this ID already exists.
  • SmolVMError: If the VM is not in a snapshotable state, uses a Windows guest, uses shared disk mode, has extra drives, has workspace mounts, or is a QEMU raw disk created for filesystem growth.

Command Execution Methods

run

Execute a command on the guest via SSH. Lazily creates an SSH client on first call and reuses it for subsequent invocations.
command
str
required
Shell command to execute on the guest.
timeout
int
default:"30"
Maximum seconds to wait for the command to complete.
shell
Literal['login', 'raw']
default:"login"
Command execution mode:
  • "login" (default): run via guest login shell
  • "raw": execute command directly with no shell wrapping
return
CommandResult
Result object containing exit code, stdout, and stderr.

Raises

  • SmolVMError: If the VM is not running or has no network.
  • CommandExecutionUnavailableError: If SSH is not available on the guest.
  • CommandBlockedError: If an on_pre_run callback vetoes the command. Any other exception raised by a pre-run callback also propagates from run().

add_callback

Register a Callback on this sandbox after construction. Returns self so calls can be chained.
callback
Callback
required
A Callback instance to attach. Its hooks will fire on subsequent run() calls.
return
SmolVM
Returns self for method chaining.

Raises

  • TypeError: If callback is not a Callback instance.

wait_for_ssh

Wait for SSH to become available on the guest.
timeout
float
default:"60.0"
Maximum seconds to wait.
return
SmolVM
Returns self for method chaining.

Raises

  • OperationTimeoutError: If SSH is not available within the timeout.
  • SmolVMError: If the VM is not running.

ssh_commands

Get ready-to-run SSH commands for this VM.
ssh_user
str | None
default:"None"
SSH user override. Defaults to the instance’s configured ssh_user.
key_path
str | Path | None
default:"None"
SSH key path override.
public_host
str | None
default:"None"
Public hostname override for remote access.
return
dict[str, str]
Dictionary mapping command names to ready-to-run SSH command strings.

Environment Variable Methods

set_env_vars

Set environment variables on a running VM. Variables are persisted in /etc/profile.d/smolvm_env.sh and affect new SSH sessions/login shells.
env_vars
dict[str, str]
required
Key/value pairs to set.
merge
bool
default:"True"
If True, merge with existing variables. If False, replace all variables.
return
list[str]
Sorted list of variable names present after the update.

unset_env_vars

Remove environment variables from a running VM.
keys
list[str]
required
Variable names to remove.
return
dict[str, str]
Mapping of removed keys to their previous values.

list_env_vars

Return SmolVM-managed environment variables for a running VM.
return
dict[str, str]
Dictionary of environment variable names to values.

Port Forwarding Methods

expose_local

Expose a guest TCP port on localhost only. Forwards 127.0.0.1:<host_port> on the host to <guest_ip>:<guest_port> inside the VM.
guest_port
int
required
Guest TCP port to expose (1-65535).
host_port
int | None
default:"None"
Host localhost port. If omitted, an available port is automatically chosen.
return
int
The host localhost port to connect to.

Raises

  • SmolVMError: If the VM is not running or has no network.
  • ValueError: If port numbers are out of valid range (1-65535).

unexpose_local

Remove a previously configured localhost-only port forward.
host_port
int
required
Host localhost port (1-65535).
guest_port
int
required
Guest TCP port (1-65535).
return
SmolVM
Returns self for method chaining.

Properties

vm_id

The VM identifier.

info

Current VM runtime information (cached). Call refresh() to update from the state store.

status

Current VM lifecycle state (cached). Values: CREATED, RUNNING, PAUSED, STOPPED, ERROR.

data_dir

Directory backing the VM state database and logs.

Utility Methods

get_ip

Return the guest IP address.
return
str
The guest VM’s IP address.

Raises

  • SmolVMError: If the VM has no network configuration.

refresh

Refresh cached VM info from the state store.
return
SmolVM
Returns self for method chaining.

can_run_commands

Whether this VM config supports command execution via SSH. Command execution requires SmolVM’s SSH init flow, enabled by booting with init=/init.
return
bool
True if SSH command execution is supported, False otherwise.

close

Release underlying SDK resources for this facade instance.

Async methods

SmolVM provides async versions of lifecycle and command methods for use in async applications.

async_start

Async version of start(). Starts the VM without blocking the event loop.

async_stop

Async version of stop().

async_run

Async version of run(). Executes a command on the guest without blocking.

async_wait_for_ssh

Async version of wait_for_ssh().

async_create_many

Create multiple sandboxes concurrently. Each sandbox is auto-configured and started.
count
int
required
Number of sandboxes to create.
memory
int | None
default:"None"
Memory for each sandbox in MiB.
disk_size
int | None
default:"None"
Disk size for each sandbox in MiB.
return
list[SmolVM]
List of started SmolVM instances.
Example:

Async context manager

SmolVM also works as an async context manager:

Context manager

SmolVM implements the context manager protocol for automatic lifecycle management:
On context entry (__enter__):
  • Auto-starts VMs created by this facade instance
On context exit (__exit__):
  • Best-effort stop if the VM is running
  • Auto-deletes only VMs created by this facade instance (not reconnected VMs)
  • Releases all resources via close()

Usage Examples

Auto-Configuration Mode

Create an SSH-ready VM with default settings:

Custom Configuration

Create a VM with specific resources:

Manual Lifecycle Management

Windows Guest

Boot a pre-installed Windows 11 qcow2 image, run a PowerShell command, and upload a file. Requires a Linux host with KVM, the OVMF + swtpm packages installed, and an image with OpenSSH Server set up. See the Windows guests guide for prerequisites and limitations.
On Windows guests, vm.run(...) executes the command in PowerShell, and vm.upload_file(...) accepts Windows-style destination paths (C:\\..., C:/..., or /C:/...).

Reconnecting to Existing VM

Port Forwarding

Pause and Resume

Environment Variables

Last modified on June 24, 2026