CubeSandbox Python SDK完全指南:pip install后10个必会API
【免费下载链接】CubeSandboxInstant, Concurrent, Secure & Lightweight Sandbox for AI Agents.项目地址: https://gitcode.com/GitHub_Trending/cu/CubeSandbox
CubeSandbox 是一个为 AI Agent 打造的即时、并发、安全且轻量级的代码沙箱平台,其官方CubeSandbox Python SDK(PyPI 包名cubesandbox)让 Python 开发者用几行代码就能创建 MicroVM 沙箱、执行代码、管理文件与快照。本文面向新手,带你用pip install完成安装后,掌握 10 个最常用的 API。
一、CubeSandbox 是什么?为什么选它?
简单来说:CubeSandbox 是"AI Agent 的安全执行环境"。它基于 MicroVM 隔离技术,每个沙箱都有独立的内核、文件系统和网络,沙箱创建耗时通常在 50ms 级别,且支持内存级快照——暂停后恢复,连运行中的变量都不用重新初始化。
官方 Python SDK 的设计目标是:Pythonic、兼容 E2B 生态、开箱即用。核心模块位于 sdk/python/cubesandbox/sandbox.py,接口文档见 sdk/python/README.md。
二、一键安装与环境配置(30秒完成)
pip install cubesandboxSDK 要求 Python 3.9+,依赖只有httpx和requests(见 pyproject.toml)。
然后通过环境变量告诉 SDK 三件事:连接谁(API 地址)、用哪个模板、代理节点在哪:
export CUBE_API_URL=http://<your-cubeapi-host>:3000 export CUBE_TEMPLATE_ID=<your-template-id> export CUBE_PROXY_NODE_IP=<your-cubeproxy-node-ip> # 远程访问时需要| 环境变量 | 必填 | 作用 |
|---|---|---|
CUBE_API_URL | ✅ | CubeAPI 管理面地址(默认http://127.0.0.1:3000) |
CUBE_TEMPLATE_ID | ✅ | 创建沙箱用的模板 ID |
CUBE_PROXY_NODE_IP | 远程 | 绕过*.cube.appDNS 直连代理节点 |
CUBE_API_KEY | 可选 | 开启鉴权的部署需要 |
也支持直接传Config对象(sdk/python/cubesandbox/_config.py),适合多集群场景。
三、10个必会API详解
1️⃣Sandbox.create()— 秒级启动一个沙箱
一切从这里开始。它封装了POST /sandboxes,50ms 内即可得到一个运行中的 MicroVM:
from cubesandbox import Sandbox with Sandbox.create() as sb: # with 块结束自动销毁 result = sb.run_code("1 + 1") print(result.text) # "2"常用参数:
template:模板 ID(不传则读CUBE_TEMPLATE_ID)timeout:空闲超时秒数env_vars:注入沙箱的环境变量(别名envs,兼容 E2B)distribution_scope:把沙箱钉到指定计算节点,如["node-a"]lifecycle:{"on_timeout": "pause", "auto_resume": True}可实现空闲自动暂停 + 透明恢复(详见 auto-resume.py)
2️⃣sb.run_code()— 在沙箱里执行代码
这是 AI Agent 场景最核心的 API,它流式返回执行结果:
result = sb.run_code("x = 42\nx * 2") print(result.text) # "84",最终表达式值 result = sb.run_code('print("hello")') print(result.logs.stdout) # ["hello\n"]亮点特性:
- 变量持久:同一个沙箱内多次
run_code共享命名空间,sb.run_code("x = 100")之后sb.run_code("x + 1")得到101 - 实时回调:
on_stdout/on_stderr/on_error可逐行流式打印输出 - 结果对象
Execution含.text、.logs、.error、.results(定义在 sdk/python/cubesandbox/_models.py)
sb.run_code('for i in range(3): print(i)', on_stdout=lambda msg: print("out:", msg.text))3️⃣sb.commands.run()— 执行 Shell 命令
不只是 Python,沙箱里可以直接跑任意 Shell 命令:
result = sb.commands.run("echo hello cube") print(result.stdout) # "hello cube\n"返回CommandResult(stdout/stderr/exit_code三件套),支持timeout、cwd、envs参数。实现见 sdk/python/cubesandbox/_commands.py,示例见 cmd.py。
4️⃣sb.files— 文件读写全家桶
通过files属性可以像操作本地文件一样操作沙箱文件系统:
sb.files.write("/tmp/hello.txt", "Hello, world!") print(sb.files.read("/tmp/hello.txt")) # "Hello, world!" sb.files.make_dir("/tmp/mydir") entries = sb.files.list("/tmp") # 目录列表 info = sb.files.stat("/tmp/hello.txt") # 元信息 print(sb.files.exists("/tmp/hello.txt")) # True sb.files.rename("/tmp/hello.txt", "/tmp/new.txt") sb.files.remove("/tmp/new.txt")还有高阶玩法:
write_files([(path, data), ...])批量写入(支持 bytes)watch_dir(path)实时监听目录变更事件(见 sdk/python/cubesandbox/_filesystem.py)
5️⃣sb.pause()+Sandbox.connect()— 内存快照:暂停与秒级恢复
这是 CubeSandbox 的招牌能力:暂停沙箱时内存状态被完整快照,恢复后连运行中的程序都"原地复活":
sb = Sandbox.create() sb.pause() # 等待快照完成(默认轮询30s) sb.pause(wait=False) # 不等待,异步执行 sb2 = Sandbox.connect(sb.sandbox_id) # connect 会自动恢复暂停的沙箱pause还支持timeout=60, interval=0.5自定义轮询。完整示例见 pause.py。
6️⃣Volume— 持久化卷:数据跨沙箱存活
沙箱会销毁,但数据不该跟着没了。Volume提供 e2b 兼容的持久卷管理:
from cubesandbox import Sandbox, Volume, VolumeMount vol = Volume.create("my-data") # 创建卷 # vol = Volume.create("my-data", driver="cos") # 指定插件 with Sandbox.create(volume_mounts={"/workspace": vol}) as sb: sb.files.write("/workspace/note.txt", "persisted!")- 同一个卷可以挂到多个沙箱,支持
VolumeMount(vol, read_only=True)按挂载点设置只读 Volume.list()/get_info()/connect()/destroy()覆盖完整生命周期- 完整 API 与错误码见 docs/volume.md 和 sdk/python/cubesandbox/_volume.py
7️⃣network=— 三层网络策略:断网、白名单、L7 注入
AI Agent 沙箱最需要安全围栏。network参数支持 L3/L4 黑白名单 + L7 精细规则:
# 彻底断网 sb = Sandbox.create(allow_internet_access=False) # 出口白名单:只允许访问指定网段 sb = Sandbox.create(network={"allow_out": ["172.67.0.0/16"]})L7 层可以按 host/path/SNI 匹配,支持审计日志和凭据注入(用Rule/Match/Action/Inject四个 dataclass 定义,见 sdk/python/cubesandbox/_policy.py):
from cubesandbox import Rule, Match, Action, Inject rules = [Rule( name="llm_api", match=Match(host="api.example.com", path="/v1/chat", sni="api.example.com"), action=Action(allow=True, audit="metadata", inject=[Inject(header="Authorization", format="Bearer ${SECRET}", secret="sk_xxx")]), )] sb = Sandbox.create(network={"allow_out": ["api.example.com"], "rules": rules})更多场景(黑名单、限制公网访问等)可参考 network_denylist.py 与 restrict_public_access.py。
8️⃣sb.get_info()/Sandbox.list()— 沙箱状态巡检
info = sb.get_info() print(info.sandbox_id, info.state) # 类型化属性(datetime、SandboxState 枚举) print(info["sandboxID"]) # 也支持原始 dict 访问 print(Sandbox.list()) # 所有运行中的沙箱 print(Sandbox.list_v2()) # v2 接口,支持服务端过滤 print(Sandbox.health()) # {"status": "ok", "sandboxes": 4}SandboxInfo提供cpu_count、memory_mb、disk_size_mb、end_at等字段,既能属性访问也能 JSON 序列化,方便接入监控面板。
9️⃣ 快照三部曲:create_snapshot()/rollback()/clone()
0.3.0 之后,CubeSandbox 把快照玩出了花——把"时间机器"做成了三个 API:
# 打快照(沙箱销毁后快照依然有效) snap = sb.create_snapshot(name="v1") # 回滚:文件系统+内存回到快照那一刻 sb.rollback(snap.snapshot_id) # 克隆:一键从当前状态派生 n 个新沙箱(支持并发) clones = sb.clone(n=4, concurrency=4)clone是 RL 训练、多路探索场景的利器,内部自动处理快照创建、并发拉起和失败回滚(部分失败会自动清理孤儿沙箱)。实现细节见 sandbox.py。
🔟 上下文管理器与sb.kill()— 优雅的生命周期收尾
with Sandbox.create() as sb: ... # with 块退出 → 自动 kill + 释放连接sb.kill():手动销毁沙箱(DELETE /sandboxes/:id)sb.set_timeout(600):动态调整空闲 TTL(传NEVER_TIMEOUT即 -1 可关闭空闲超时)sb.get_host(port):拿到沙箱端点的虚拟域名{port}-{id}.cube.app,把沙箱里的 Web 服务直接暴露给浏览器- 异常体系清晰:
SandboxNotFoundError、TemplateNotFoundError、ApiError等(sdk/python/cubesandbox/_exceptions.py)
四、常见问题(新手必看)
| 现象 | 原因与解决 |
|---|---|
Template not found | 模板 ID 错误,检查CUBE_TEMPLATE_ID |
Connection refused | CubeAPI 不可达,确认CUBE_API_URL端口 3000 通 |
SSL: CERTIFICATE_VERIFY_FAILED | 自建 CA 场景,设置SSL_CERT_FILE指向根证书 |
| 远程访问域名解析失败 | 设置CUBE_PROXY_NODE_IP启用 IP 直连绕过 DNS |
更多示例脚本(自动暂停/自动销毁、环境变量注入等)都在 examples/code-sandbox-quickstart/ 目录下,配套中文教程见 README_zh.md。
五、写在最后
回顾一下这 10 个必会 API 的地图:
Sandbox.create()创建 → 2.run_code()执行代码 → 3.commands.run()跑 Shell → 4.files文件操作 → 5.pause()/connect()快照恢复 → 6.Volume持久化 → 7.network安全围栏 → 8.get_info()/list()巡检 → 9. 快照/回滚/克隆 → 10. 上下文管理器优雅收尾
从pip install cubesandbox到给 AI Agent 搭一个"用完即焚、秒级恢复"的安全执行环境,你只需要一个下午。快去试试吧 🚀
【免费下载链接】CubeSandboxInstant, Concurrent, Secure & Lightweight Sandbox for AI Agents.项目地址: https://gitcode.com/GitHub_Trending/cu/CubeSandbox
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考