cubesandbox-ai-sandbox
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCubeSandbox AI Sandbox Skill
CubeSandbox AI沙箱Skill
Skill by ara.so — Daily 2026 Skills collection.
CubeSandbox is a high-performance secure sandbox service built on RustVMM and KVM. It provides hardware-isolated (dedicated Guest OS kernel) sandbox environments that start in under 60ms, consume less than 5MB memory overhead per instance, and are fully compatible with the E2B SDK — making it a drop-in replacement for E2B with better performance and true VM-level isolation.
该Skill由ara.so提供 — 属于Daily 2026 Skills合集。
CubeSandbox是一款基于RustVMM和KVM构建的高性能安全沙箱服务。它提供硬件隔离(独立Guest OS内核)的沙箱环境,启动时间不到60毫秒,每个实例内存开销不足5MB,且完全兼容E2B SDK — 可直接替代E2B,拥有更优性能和真正的VM级隔离能力。
What CubeSandbox Does
CubeSandbox功能特性
- Spins up KVM-backed microVMs in <60ms using snapshot cloning + CoW memory
- Provides thousands of concurrent isolated sandboxes per node (<5MB RAM overhead each)
- Offers E2B SDK compatibility — just change one env var to migrate
- Enforces kernel-level network isolation via eBPF (CubeVS)
- Supports single-node and multi-node cluster deployments
- Enables code execution, shell commands, file ops, browser automation, and RL training
- 利用快照克隆+CoW内存技术,在<60毫秒内启动基于KVM的微虚拟机
- 单节点可支持数千个并发隔离沙箱(每个仅<5MB内存开销)
- 兼容E2B SDK — 仅需修改一个环境变量即可完成迁移
- 通过eBPF(CubeVS)实现内核级网络隔离
- 支持单节点和多节点集群部署
- 支持代码执行、Shell命令、文件操作、浏览器自动化及强化学习训练
Requirements
环境要求
- x86_64 Linux with KVM enabled (bare metal, WSL2, or cloud bare-metal)
- Not supported on shared VMs that don't allow nested virtualization
Check KVM availability:
bash
ls /dev/kvm && echo "KVM available"- 启用KVM的x86_64 Linux系统(裸机、WSL2或云裸机)
- 不支持不允许嵌套虚拟化的共享虚拟机
检查KVM可用性:
bash
ls /dev/kvm && echo "KVM available"Installation
安装步骤
Option A: Development VM (WSL2 / no bare metal)
选项A:开发虚拟机(WSL2 / 无裸机环境)
bash
git clone https://github.com/tencentcloud/CubeSandbox.git
cd CubeSandbox/dev-env
./prepare_image.sh # one-time: downloads runtime image
./run_vm.sh # start the dev VM (keep terminal open)bash
git clone https://github.com/tencentcloud/CubeSandbox.git
cd CubeSandbox/dev-env
./prepare_image.sh # 一次性操作:下载运行时镜像
./run_vm.sh # 启动开发虚拟机(保持终端打开)In a second terminal:
在第二个终端中执行:
./login.sh # shell into the dev VM
undefined./login.sh # 登录到开发虚拟机
undefinedOption B: Bare-Metal / Cloud Server
选项B:裸机 / 云服务器
Inside the target Linux host (or the dev VM from Option A):
bash
undefined在目标Linux主机(或选项A中的开发虚拟机)内执行:
bash
undefinedGlobal users:
全球用户:
Mainland China mirror:
中国大陆镜像:
curl -sL https://cnb.cool/CubeSandbox/CubeSandbox/-/git/raw/master/deploy/one-click/online-install.sh | MIRROR=cn bash
This installs `cubemastercli` and starts the CubeAPI service on port 3000.
---curl -sL https://cnb.cool/CubeSandbox/CubeSandbox/-/git/raw/master/deploy/one-click/online-install.sh | MIRROR=cn bash
此命令将安装`cubemastercli`并在3000端口启动CubeAPI服务。
---Key CLI: cubemastercli
cubemastercli核心CLI工具:cubemastercli
cubemastercliCreate a Template from a Docker Image
从Docker镜像创建模板
bash
cubemastercli tpl create-from-image \
--image ccr.ccs.tencentyun.com/ags-image/sandbox-code:latest \
--writable-layer-size 1G \
--expose-port 49999 \
--expose-port 49983 \
--probe 49999bash
cubemastercli tpl create-from-image \
--image ccr.ccs.tencentyun.com/ags-image/sandbox-code:latest \
--writable-layer-size 1G \
--expose-port 49999 \
--expose-port 49983 \
--probe 49999Returns a job_id
返回一个job_id
undefinedundefinedWatch Build Progress
查看构建进度
bash
cubemastercli tpl watch --job-id <job_id>bash
cubemastercli tpl watch --job-id <job_id>Wait for status: READY
等待状态变为:READY
Note the template_id from output
记录输出中的template_id
undefinedundefinedList Templates
列出所有模板
bash
cubemastercli tpl listbash
cubemastercli tpl listDelete a Template
删除模板
bash
cubemastercli tpl delete --template-id <template_id>bash
cubemastercli tpl delete --template-id <template_id>List Running Sandboxes
列出运行中的沙箱
bash
cubemastercli sandbox listbash
cubemastercli sandbox listKill a Sandbox
终止沙箱
bash
cubemastercli sandbox kill --sandbox-id <sandbox_id>bash
cubemastercli sandbox kill --sandbox-id <sandbox_id>Environment Variables
环境变量配置
bash
undefinedbash
undefinedRequired for SDK usage
SDK使用必填
export E2B_API_URL="http://127.0.0.1:3000" # CubeAPI endpoint
export E2B_API_KEY="dummy" # any non-empty string (auth not required locally)
export CUBE_TEMPLATE_ID="<your-template-id>" # from cubemastercli tpl watch output
export SSL_CERT_FILE="/root/.local/share/mkcert/rootCA.pem" # local CA cert
---export E2B_API_URL="http://127.0.0.1:3000" # CubeAPI端点
export E2B_API_KEY="dummy" # 任意非空字符串(本地无需认证)
export CUBE_TEMPLATE_ID="<your-template-id>" # 来自cubemastercli tpl watch的输出
export SSL_CERT_FILE="/root/.local/share/mkcert/rootCA.pem" # 本地CA证书
---Python SDK Usage (E2B-Compatible)
Python SDK使用(兼容E2B)
Install the E2B SDK:
bash
pip install e2b-code-interpreter安装E2B SDK:
bash
pip install e2b-code-interpreterBasic Code Execution
基础代码执行
python
import os
from e2b_code_interpreter import Sandbox
template_id = os.environ["CUBE_TEMPLATE_ID"]
with Sandbox.create(template=template_id) as sandbox:
result = sandbox.run_code("print('Hello from CubeSandbox!')")
print(result.text)
# Output: Hello from CubeSandbox!python
import os
from e2b_code_interpreter import Sandbox
template_id = os.environ["CUBE_TEMPLATE_ID"]
with Sandbox.create(template=template_id) as sandbox:
result = sandbox.run_code("print('Hello from CubeSandbox!')")
print(result.text)
# 输出:Hello from CubeSandbox!Run Python with Return Values
执行Python并获取返回值
python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
result = sandbox.run_code("""
import math
data = [1, 4, 9, 16, 25]
roots = [math.sqrt(x) for x in data]
print(roots)
roots
""")
print(result.text) # stdout
print(result.results) # return value of last expressionpython
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
result = sandbox.run_code("""
import math
data = [1, 4, 9, 16, 25]
roots = [math.sqrt(x) for x in data]
print(roots)
roots
""")
print(result.text) # 标准输出
print(result.results) # 最后一个表达式的返回值Shell Command Execution
Shell命令执行
python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
# Run shell commands
result = sandbox.run_code("import subprocess; print(subprocess.check_output(['ls', '-la', '/'], text=True))")
print(result.text)python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
# 执行Shell命令
result = sandbox.run_code("import subprocess; print(subprocess.check_output(['ls', '-la', '/'], text=True))")
print(result.text)File Operations
文件操作
python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
# Write a file
sandbox.files.write("/tmp/hello.txt", "Hello, CubeSandbox!")
# Read the file back
content = sandbox.files.read("/tmp/hello.txt")
print(content)
# List directory
entries = sandbox.files.list("/tmp")
for entry in entries:
print(entry.name, entry.type)python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
# 写入文件
sandbox.files.write("/tmp/hello.txt", "Hello, CubeSandbox!")
# 读取文件
content = sandbox.files.read("/tmp/hello.txt")
print(content)
# 列出目录内容
entries = sandbox.files.list("/tmp")
for entry in entries:
print(entry.name, entry.type)Install Packages at Runtime
运行时安装依赖包
python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
# Install a package inside the sandbox
result = sandbox.run_code("import subprocess; subprocess.run(['pip', 'install', 'requests'], capture_output=True)")
# Use the installed package
result = sandbox.run_code("""
import requests
r = requests.get("https://httpbin.org/get")
print(r.status_code)
""")
print(result.text)python
import os
from e2b_code_interpreter import Sandbox
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
# 在沙箱内安装依赖包
result = sandbox.run_code("import subprocess; subprocess.run(['pip', 'install', 'requests'], capture_output=True)")
# 使用已安装的包
result = sandbox.run_code("""
import requests
r = requests.get("https://httpbin.org/get")
print(r.status_code)
""")
print(result.text)Persistent Sandbox (Manual Lifecycle)
持久化沙箱(手动生命周期管理)
python
import os
from e2b_code_interpreter import Sandboxpython
import os
from e2b_code_interpreter import SandboxCreate without context manager for explicit control
不使用上下文管理器,手动控制生命周期
sandbox = Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"])
try:
sandbox.run_code("x = 42")
result = sandbox.run_code("print(x)") # state persists within session
print(result.text) # 42
finally:
sandbox.kill()
undefinedsandbox = Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"])
try:
sandbox.run_code("x = 42")
result = sandbox.run_code("print(x)") # 会话内状态持久化
print(result.text) # 42
finally:
sandbox.kill()
undefinedConcurrent Sandboxes
并发沙箱
python
import os
import asyncio
from e2b_code_interpreter import AsyncSandbox
template_id = os.environ["CUBE_TEMPLATE_ID"]
async def run_task(task_id: int, code: str):
async with await AsyncSandbox.create(template=template_id) as sandbox:
result = await sandbox.run_code(code)
return task_id, result.text
async def main():
tasks = [
run_task(i, f"print('Task {i} result:', {i} ** 2)")
for i in range(10)
]
results = await asyncio.gather(*tasks)
for task_id, output in results:
print(f"Task {task_id}: {output.strip()}")
asyncio.run(main())python
import os
import asyncio
from e2b_code_interpreter import AsyncSandbox
template_id = os.environ["CUBE_TEMPLATE_ID"]
async def run_task(task_id: int, code: str):
async with await AsyncSandbox.create(template=template_id) as sandbox:
result = await sandbox.run_code(code)
return task_id, result.text
async def main():
tasks = [
run_task(i, f"print('Task {i} result:', {i} ** 2)")
for i in range(10)
]
results = await asyncio.gather(*tasks)
for task_id, output in results:
print(f"Task {task_id}: {output.strip()}")
asyncio.run(main())Custom Template Creation
自定义模板创建
From a Custom Dockerfile
从自定义Dockerfile创建
Build and push your image, then create a template:
bash
undefined构建并推送镜像,然后创建模板:
bash
undefinedBuild and push your image
构建并推送镜像
docker build -t myregistry.example.com/my-sandbox:latest .
docker push myregistry.example.com/my-sandbox:latest
docker build -t myregistry.example.com/my-sandbox:latest .
docker push myregistry.example.com/my-sandbox:latest
Create CubeSandbox template
创建CubeSandbox模板
cubemastercli tpl create-from-image
--image myregistry.example.com/my-sandbox:latest
--writable-layer-size 2G
--expose-port 49999
--expose-port 8080
--probe 49999
--image myregistry.example.com/my-sandbox:latest
--writable-layer-size 2G
--expose-port 49999
--expose-port 8080
--probe 49999
cubemastercli tpl create-from-image
--image myregistry.example.com/my-sandbox:latest
--writable-layer-size 2G
--expose-port 49999
--expose-port 8080
--probe 49999
--image myregistry.example.com/my-sandbox:latest
--writable-layer-size 2G
--expose-port 49999
--expose-port 8080
--probe 49999
Watch until READY
等待状态变为READY
cubemastercli tpl watch --job-id <job_id>
undefinedcubemastercli tpl watch --job-id <job_id>
undefinedTemplate with Multiple Exposed Ports
多端口暴露模板
bash
cubemastercli tpl create-from-image \
--image ccr.ccs.tencentyun.com/ags-image/sandbox-code:latest \
--writable-layer-size 1G \
--expose-port 49999 \ # code interpreter
--expose-port 49983 \ # file server
--expose-port 3000 \ # custom app port
--probe 49999 # health check portbash
cubemastercli tpl create-from-image \
--image ccr.ccs.tencentyun.com/ags-image/sandbox-code:latest \
--writable-layer-size 1G \
--expose-port 49999 \ # 代码解释器
--expose-port 49983 \ # 文件服务器
--expose-port 3000 \ # 自定义应用端口
--probe 49999 # 健康检查端口REST API (CubeAPI)
REST API(CubeAPI)
CubeAPI runs on port 3000 and is E2B-compatible. Example direct calls:
bash
undefinedCubeAPI运行在3000端口,兼容E2B。示例直接调用:
bash
undefinedCreate a sandbox
创建沙箱
curl -s -X POST http://127.0.0.1:3000/sandboxes
-H "Content-Type: application/json"
-H "X-API-Key: dummy"
-d "{"templateID": "$CUBE_TEMPLATE_ID"}"
-H "Content-Type: application/json"
-H "X-API-Key: dummy"
-d "{"templateID": "$CUBE_TEMPLATE_ID"}"
curl -s -X POST http://127.0.0.1:3000/sandboxes
-H "Content-Type: application/json"
-H "X-API-Key: dummy"
-d "{"templateID": "$CUBE_TEMPLATE_ID"}"
-H "Content-Type: application/json"
-H "X-API-Key: dummy"
-d "{"templateID": "$CUBE_TEMPLATE_ID"}"
List sandboxes
列出沙箱
curl -s http://127.0.0.1:3000/sandboxes
-H "X-API-Key: dummy"
-H "X-API-Key: dummy"
curl -s http://127.0.0.1:3000/sandboxes
-H "X-API-Key: dummy"
-H "X-API-Key: dummy"
Delete a sandbox
删除沙箱
curl -s -X DELETE "http://127.0.0.1:3000/sandboxes/<sandbox_id>"
-H "X-API-Key: dummy"
-H "X-API-Key: dummy"
---curl -s -X DELETE "http://127.0.0.1:3000/sandboxes/<sandbox_id>"
-H "X-API-Key: dummy"
-H "X-API-Key: dummy"
---Architecture Overview
架构概述
| Component | Role |
|---|---|
| CubeAPI | Rust REST gateway, E2B-compatible, port 3000 |
| CubeMaster | Cluster orchestrator, dispatches to Cubelets, manages scheduling |
| Cubelet | Per-node agent, manages local microVM lifecycle |
| CubeVS | eBPF-powered virtual switch for inter-sandbox network isolation |
| CubeProxy | Reverse proxy routing external traffic to correct sandbox instances |
| 组件 | 角色 |
|---|---|
| CubeAPI | Rust编写的REST网关,兼容E2B,端口3000 |
| CubeMaster | 集群编排器,调度任务到Cubelets,管理调度逻辑 |
| Cubelet | 单节点代理,管理本地微虚拟机生命周期 |
| CubeVS | 基于eBPF的虚拟交换机,实现沙箱间网络隔离 |
| CubeProxy | 反向代理,将外部流量路由到对应沙箱实例 |
Common Patterns
常用模式
Pattern: AI Agent Code Execution Loop
模式:AI Agent代码执行循环
python
import os
from e2b_code_interpreter import Sandbox
def run_agent_code(llm_generated_code: str) -> dict:
"""Safely execute LLM-generated code in an isolated VM."""
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
result = sandbox.run_code(llm_generated_code)
return {
"stdout": result.text,
"results": [str(r) for r in result.results],
"error": result.error.traceback if result.error else None,
}python
import os
from e2b_code_interpreter import Sandbox
def run_agent_code(llm_generated_code: str) -> dict:
"""在隔离虚拟机中安全执行大语言模型生成的代码。"""
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
result = sandbox.run_code(llm_generated_code)
return {
"stdout": result.text,
"results": [str(r) for r in result.results],
"error": result.error.traceback if result.error else None,
}Example agent loop
示例Agent循环
code_snippets = [
"import sys; print(sys.version)",
"2 + 2",
"raise ValueError('test error')",
]
for code in code_snippets:
output = run_agent_code(code)
print("stdout:", output["stdout"])
print("error: ", output["error"])
print("---")
undefinedcode_snippets = [
"import sys; print(sys.version)",
"2 + 2",
"raise ValueError('test error')",
]
for code in code_snippets:
output = run_agent_code(code)
print("stdout:", output["stdout"])
print("error: ", output["error"])
print("---")
undefinedPattern: Stateful Multi-Turn Execution
模式:有状态多轮执行
python
import os
from e2b_code_interpreter import Sandboxpython
import os
from e2b_code_interpreter import SandboxKeep sandbox alive across multiple turns
保持沙箱存活以支持多轮交互
with Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
turns = [
"import pandas as pd\ndf = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})",
"df['c'] = df['a'] + df['b']",
"print(df.to_string())",
]
for turn in turns:
result = sandbox.run_code(turn)
if result.text:
print(result.text)
if result.error:
print("ERROR:", result.error.value)
break
undefinedwith Sandbox.create(template=os.environ["CUBE_TEMPLATE_ID"]) as sandbox:
turns = [
"import pandas as pd\ndf = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6]})",
"df['c'] = df['a'] + df['b']",
"print(df.to_string())",
]
for turn in turns:
result = sandbox.run_code(turn)
if result.text:
print(result.text)
if result.error:
print("ERROR:", result.error.value)
break
undefinedPattern: E2B Migration (Zero Code Change)
模式:E2B迁移(零代码修改)
bash
undefinedbash
undefinedBefore (E2B cloud):
之前(E2B云服务):
export E2B_API_KEY="your_e2b_key"
export E2B_API_KEY="your_e2b_key"
After (CubeSandbox — only env var changes):
之后(CubeSandbox — 仅修改环境变量):
export E2B_API_URL="http://your-cubesandbox-host:3000"
export E2B_API_KEY="dummy"
export SSL_CERT_FILE="/root/.local/share/mkcert/rootCA.pem"
Your existing E2B Python/JS code works unchanged.
---export E2B_API_URL="http://your-cubesandbox-host:3000"
export E2B_API_KEY="dummy"
export SSL_CERT_FILE="/root/.local/share/mkcert/rootCA.pem"
您现有的E2B Python/JS代码无需修改即可直接运行。
---Troubleshooting
故障排查
KVM Not Available
KVM不可用
bash
undefinedbash
undefinedCheck KVM support
检查KVM支持
ls /dev/kvm
ls /dev/kvm
If missing on WSL2, enable in Windows:
如果WSL2中缺失,在Windows中启用:
System Properties → Advanced → Performance → Enable virtualization in BIOS/WSL
系统属性 → 高级 → 性能 → 在BIOS/WSL中启用虚拟化
undefinedundefinedTemplate Stuck in Building State
模板卡在构建状态
bash
undefinedbash
undefinedCheck logs
查看日志
cubemastercli tpl watch --job-id <job_id>
cubemastercli tpl watch --job-id <job_id>
If image pull fails, verify registry accessibility from the host
如果镜像拉取失败,验证主机是否能访问镜像仓库
curl -I https://ccr.ccs.tencentyun.com
undefinedcurl -I https://ccr.ccs.tencentyun.com
undefinedSandbox Creation Timeout
沙箱创建超时
bash
undefinedbash
undefinedCheck service health
检查服务健康状态
Check available resources
检查可用资源
free -h
df -h /
free -h
df -h /
Restart the service if needed
必要时重启服务
systemctl restart cubemaster # or the relevant service unit
undefinedsystemctl restart cubemaster # 或对应的服务单元
undefinedSSL Certificate Errors
SSL证书错误
bash
undefinedbash
undefinedEnsure the CA cert is exported
确保CA证书已导出
export SSL_CERT_FILE="/root/.local/share/mkcert/rootCA.pem"
export SSL_CERT_FILE="/root/.local/share/mkcert/rootCA.pem"
Verify the file exists
验证文件存在
ls -la $SSL_CERT_FILE
undefinedls -la $SSL_CERT_FILE
undefinedPort Already in Use
端口已被占用
bash
undefinedbash
undefinedCheck what's on port 3000
检查3000端口占用情况
ss -tlnp | grep 3000
ss -tlnp | grep 3000
CubeAPI default port; reconfigure if needed before install
CubeAPI默认端口;安装前可按需重新配置
undefinedundefinedHigh Memory Usage
内存占用过高
bash
undefinedbash
undefinedList all running sandboxes and kill idle ones
列出所有运行中的沙箱并终止闲置沙箱
cubemastercli sandbox list
cubemastercli sandbox kill --sandbox-id <sandbox_id>
---cubemastercli sandbox list
cubemastercli sandbox kill --sandbox-id <sandbox_id>
---Examples Directory
示例目录
The directory in the repo covers:
examples/- — basic Python/JS code running
code-execution/ - — shell exec patterns
shell-commands/ - — read/write/list files
file-operations/ - — Playwright inside sandbox
browser-automation/ - — eBPF egress filtering
network-policies/ - — suspend and resume sandboxes
pause-resume/ - — OpenClaw integration
openclaw/ - — reinforcement learning / SWE-Bench workflows
rl-training/
bash
undefined仓库中的目录包含以下示例:
examples/- — 基础Python/JS代码运行示例
code-execution/ - — Shell命令执行模式
shell-commands/ - — 文件读写/列表示例
file-operations/ - — 沙箱内Playwright自动化示例
browser-automation/ - — eBPF出口过滤示例
network-policies/ - — 沙箱挂起与恢复示例
pause-resume/ - — OpenClaw集成示例
openclaw/ - — 强化学习/SWE-Bench工作流示例
rl-training/
bash
undefinedBrowse examples
浏览示例
ls examples/
---ls examples/
---Resources
资源链接
- Docs: https://docs.cubesandbox.ai/
- Quick Start:
./docs/guide/quickstart.md - Templates Guide:
./docs/guide/templates.md - Changelog:
./docs/changelog.md - China Mirror: https://cnb.cool/CubeSandbox/CubeSandbox
- 文档: https://docs.cubesandbox.ai/
- 快速开始:
./docs/guide/quickstart.md - 模板指南:
./docs/guide/templates.md - 更新日志:
./docs/changelog.md - 中国大陆镜像: https://cnb.cool/CubeSandbox/CubeSandbox