Overview
TheSmolVM 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
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.ID of an existing VM to reconnect to. Mutually exclusive with
config.Disk image to boot. Accepts:
- A published S3 image URI (
s3://bucket/images/alpine/) — the manifest defines the OS, soos=must be omitted. - A local
qcow2file path (/var/lib/vms/win11.qcow2,~/win11/disk.qcow2) orfile://URI — requiresos=since the file alone doesn’t self-identify.
config and vm_id. Local images are only supported for os="windows" in this release; see Windows guests.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.
Override the default data directory for VM state storage.
Override the default socket directory.
Runtime backend override. Options:
"firecracker", "qemu", or "auto".Guest memory in MiB for auto-config mode (when both
config and vm_id are omitted). Default is 512 MiB.Root filesystem size in MiB for auto-config mode. Default is 512 MiB. Minimum is 64 MiB.
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 private key path. If omitted, SmolVM first tries default SSH auth, then falls back to
~/.smolvm/keys/id_ed25519.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.
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 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 bothconfigandvm_idare provided, or ifmemory/disk_sizeare set outside auto-config mode.
Class Methods
from_id
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 identifier to reconnect to.
A SmolVM instance bound to the existing VM.
Raises
VMNotFoundError: If no VM with this ID exists.
from_image
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 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.Custom VM identifier. Defaults to an auto-generated name using
name_prefix.Prefix used when SmolVM generates a
vm_id.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.Guest architecture (
"amd64" or "arm64"). Defaults to the image’s recorded arch, otherwise the host arch.Number of guest vCPUs.
Guest memory in MiB.
Guest OS hint used by SmolVM’s lifecycle helpers (
"alpine", "ubuntu", or "windows").QEMU network mode. Use
"slirp" to enable user-mode networking with port_forwards. Ignored for non-QEMU backends.Host-to-guest port forwards. Only valid with
backend="qemu" and network="slirp".Vsock configuration for host-to-guest control or custom services.
Host-to-guest control channel for
run() and file transfers. See control channel.Whether each VM gets its own per-VM disk overlay (
"isolated") or shares the base image ("shared").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.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 for
run(). Ignored when the image is not SSH-capable.SSH private key path.
SSH password. Use this for images that ship password-only SSH.
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, orport_forwardsare incompatible with the image (for example,port_forwardsoutside 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=Trueon a qcow2 image, adisk_size_mbsmaller than the current disk, ore2fsprogsmissing on the host.
Example
browser
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.
A started browser sandbox with
cdp_url, and with viewer_url plus display_url when headless=False.desktop
viewer_url to open the desktop in your browser, or display_url for a VNC-compatible computer-use agent.
A started desktop sandbox with
viewer_url and display_url.from_snapshot
The identifier of the snapshot to restore.
Resume the restored VM immediately. When False, the VM is restored in a paused state.
Allow restoring a snapshot that was already restored before. By default, each snapshot can only be restored once.
Override the default data directory.
Override the default socket directory.
Runtime backend override.
SSH user for command execution.
SSH private key path.
A SmolVM instance bound to the restored VM.
Raises
SnapshotNotFoundError: If no snapshot with this ID exists.SmolVMError: If the snapshot was already restored (useforce=Trueto override).
Lifecycle Methods
start
env_vars, they are injected into the guest via SSH after boot completes.
Maximum seconds to wait for boot to complete.
Returns
self for method chaining.Raises
SmolVMError: Ifenv_varsis set but the image does not support SSH (missinginit=/initin boot args).
stop
Seconds to wait for graceful shutdown.
Returns
self for method chaining.delete
pause
resume() to continue execution.
Returns
self for method chaining.Raises
SmolVMError: If the VM is not in a pausable state (must be running).
resume
Returns
self for method chaining.Raises
SmolVMError: If the VM is not paused.
snapshot
resume_source=True is set.
Custom snapshot identifier. If omitted, SmolVM generates one automatically (for example,
snap-my-vm-1717012345). Must contain only lowercase letters, numbers, hyphens, and underscores.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.
Resume the source VM after snapshot creation. When False, the VM stays paused.
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
Shell command to execute on the guest.
Maximum seconds to wait for the command to complete.
Command execution mode:
"login"(default): run via guest login shell"raw": execute command directly with no shell wrapping
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 anon_pre_runcallback vetoes the command. Any other exception raised by a pre-run callback also propagates fromrun().
add_callback
Callback on this sandbox after construction. Returns self so calls can be chained.
A
Callback instance to attach. Its hooks will fire on subsequent run() calls.Returns
self for method chaining.Raises
TypeError: Ifcallbackis not aCallbackinstance.
wait_for_ssh
Maximum seconds to wait.
Returns
self for method chaining.Raises
OperationTimeoutError: If SSH is not available within the timeout.SmolVMError: If the VM is not running.
ssh_commands
SSH user override. Defaults to the instance’s configured ssh_user.
SSH key path override.
Public hostname override for remote access.
Dictionary mapping command names to ready-to-run SSH command strings.
Environment Variable Methods
set_env_vars
/etc/profile.d/smolvm_env.sh and affect new SSH sessions/login shells.
Key/value pairs to set.
If True, merge with existing variables. If False, replace all variables.
Sorted list of variable names present after the update.
unset_env_vars
Variable names to remove.
Mapping of removed keys to their previous values.
list_env_vars
Dictionary of environment variable names to values.
Port Forwarding Methods
expose_local
127.0.0.1:<host_port> on the host to <guest_ip>:<guest_port> inside the VM.
Guest TCP port to expose (1-65535).
Host localhost port. If omitted, an available port is automatically chosen.
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
Host localhost port (1-65535).
Guest TCP port (1-65535).
Returns
self for method chaining.Properties
vm_id
info
refresh() to update from the state store.
status
CREATED, RUNNING, PAUSED, STOPPED, ERROR.
data_dir
Utility Methods
get_ip
The guest VM’s IP address.
Raises
SmolVMError: If the VM has no network configuration.
refresh
Returns
self for method chaining.can_run_commands
init=/init.
True if SSH command execution is supported, False otherwise.
close
Async methods
SmolVM provides async versions of lifecycle and command methods for use in async applications.async_start
start(). Starts the VM without blocking the event loop.
async_stop
stop().
async_run
run(). Executes a command on the guest without blocking.
async_wait_for_ssh
wait_for_ssh().
async_create_many
Number of sandboxes to create.
Memory for each sandbox in MiB.
Disk size for each sandbox in MiB.
List of started SmolVM instances.
Async context manager
SmolVM also works as an async context manager:Context manager
SmolVM implements the context manager protocol for automatic lifecycle management:__enter__):
- Auto-starts VMs created by this facade instance
__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 11qcow2 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.
vm.run(...) executes the command in PowerShell, and vm.upload_file(...) accepts Windows-style destination paths (C:\\..., C:/..., or /C:/...).
