阿里开源 OpenSandbox 快速入门

2026年3月2日

10 分钟入门阿里开源通用沙箱平台,打造你的第一个隔离执行环境

难度: ⭐⭐☆☆☆ | 时长: 10 分钟 | 收获: 掌握 OpenSandbox 核心用法,能快速构建隔离执行环境


目标读者

  • 1-3 年后端开发者
  • 想为 AI Agent 添加安全代码执行能力的工程师
  • 对沙箱技术感兴趣的技术人员

核心依赖

  • Python 3.10+
  • Docker Desktop
  • opensandbox - Python SDK
  • opensandbox-server - 沙箱服务
  • opensandbox-code-interpreter - 代码解释器
# 安装依赖
uv pip install opensandbox opensandbox-server opensandbox-code-interpreter

TIP

推荐使用 uv 作为包管理工具,也可以用 pip 替代


项目结构

OpenSandbox/
├── sdks/                    # 多语言 SDK
│   ├── sandbox/python/      # 基础沙箱 SDK
│   └── code-interpreter/    # 代码解释器 SDK
├── server/                  # 沙箱生命周期管理服务
├── examples/                # 集成示例 (Claude Code, Playwright 等)
├── components/              # 核心组件 (ingress, egress)
└── specs/                   # API 规范定义

1. 启动沙箱服务

安装完成后,一条命令启动本地沙箱服务:

# 初始化配置文件(可选,使用默认配置可跳过)
opensandbox-server init-config ~/.sandbox.toml --example docker

# 启动服务
opensandbox-server

服务默认监听 http://localhost:8080,不需要额外配置即可本地开发测试。

WARNING

生产环境建议使用 Kubernetes 部署,详见后文「进阶方向」


2. 创建第一个沙箱

import asyncio
from opensandbox import Sandbox
from opensandbox.config import ConnectionConfig

async def main():
    # 连接本地服务(不配置 domain 时默认连接 localhost:8080)
    config = ConnectionConfig()

    # 创建沙箱,指定镜像
    sandbox = await Sandbox.create(
        "ubuntu:latest",
        connection_config=config
    )

    async with sandbox:
        # 执行命令
        result = await sandbox.commands.run("echo 'Hello OpenSandbox!'")
        print(result.logs.stdout[0].text)  # Hello OpenSandbox!

        # 清理资源
        await sandbox.kill()

asyncio.run(main())

核心流程就三步:创建 → 执行 → 清理


3. 文件操作

沙箱内置完整的文件系统支持,写入、读取、搜索、删除都可以:

from opensandbox.models import WriteEntry

async def file_operations():
    # 写入文件
    await sandbox.files.write_files([
        WriteEntry(
            path="/tmp/demo.txt",
            data="Hello from sandbox!",
            mode=644
        )
    ])

    # 读取文件
    content = await sandbox.files.read_file("/tmp/demo.txt")
    print(content)  # Hello from sandbox!

    # 搜索文件
    files = await sandbox.files.search(
        path="/tmp",
        pattern="*.txt"
    )
    for f in files:
        print(f"Found: {f.path}")

WriteEntrymode 参数支持八进制权限设置,比如 644755


4. 沙箱生命周期管理

沙箱创建后会自动管理生命周期,支持续期、暂停、恢复:

from datetime import timedelta

# 续期:重置过期时间
await sandbox.renew(timedelta(minutes=30))

# 暂停:挂起所有进程
await sandbox.pause()

# 恢复:从暂停状态恢复
resumed = await Sandbox.resume(
    sandbox_id=sandbox.id,
    connection_config=config
)

# 查看当前状态
info = await sandbox.get_info()
print(f"State: {info.status.state}")  # RUNNING, PAUSED, TERMINATED

TIP

沙箱默认 10 分钟自动过期,记得根据实际需求设置合适的超时时间


5. 构建 Code Interpreter

如果你需要实现类似 ChatGPT 的代码解释器功能,OpenSandbox 提供了开箱即用的 SDK:

import asyncio
from datetime import timedelta
from code_interpreter import CodeInterpreter, SupportedLanguage
from opensandbox import Sandbox

async def main():
    # 创建沙箱,指定 code-interpreter 镜像
    sandbox = await Sandbox.create(
        "opensandbox/code-interpreter:v1.0.1",
        entrypoint=["/opt/opensandbox/code-interpreter.sh"],
        timeout=timedelta(minutes=10),
    )

    async with sandbox:
        # 创建代码解释器
        interpreter = await CodeInterpreter.create(sandbox)

        # 执行 Python 代码
        result = await interpreter.codes.run(
            """
            import sys
            print(sys.version)

            # 简单的数据处理
            data = [1, 2, 3, 4, 5]
            result = sum(data)
            result
            """,
            language=SupportedLanguage.PYTHON,
        )

        # 打印执行结果
        print(result.result[0].text)      # 15
        print(result.logs.stdout[0].text) # 3.11.14

    await sandbox.kill()

asyncio.run(main())

CodeInterpreter 会自动处理代码执行、结果返回、错误处理,你只需要调用 codes.run() 即可。


6. 常见问题

Q1: 连接超时

# 增加超时时间
config = ConnectionConfig(
    request_timeout=timedelta(seconds=60)
)

Q2: 镜像拉取失败

检查 Docker 镜像仓库是否正常:

docker pull ubuntu:latest

国内建议配置镜像加速器。

Q3: 权限问题

沙箱内执行命令默认是 root 权限,但如果需要特定用户:

sandbox = await Sandbox.create(
    "ubuntu:latest",
    entrypoint=["su", "-", "ubuntu", "-c", "tail -f /dev/null"]
)

Q4: 网络访问受限

创建沙箱时可以配置网络策略:

from opensandbox.models.sandboxes import NetworkPolicy, NetworkRule

sandbox = await Sandbox.create(
    "python:3.11",
    network_policy=NetworkPolicy(
        defaultAction="deny",
        egress=[
            NetworkRule(action="allow", target="pypi.org"),
            NetworkRule(action="allow", target="*.github.com"),
        ]
    )
)

Q5: 如何查看沙箱日志

# 获取沙箱详细信息
info = await sandbox.get_info()
print(info.status)

Q6: 同步模式怎么用

如果不方便用 async/await,SDK 提供了同步版本:

from opensandbox import SandboxSync

sandbox = SandboxSync.create("ubuntu:latest")
with sandbox:
    result = sandbox.commands.run("echo 'sync mode'")
    print(result.logs.stdout[0].text)

7. 进阶方向

Kubernetes 部署

生产环境推荐使用 Kubernetes,官方提供了完整的 Helm Chart:

helm repo add opensandbox https://alibaba.github.io/opensandbox-charts
helm install opensandbox opensandbox/opensandbox

详见 kubernetes-sigs/agent-sandbox

多语言 SDK

OpenSandbox 不仅支持 Python,还提供了多种语言的 SDK:

  • Java/Kotlin: opensandbox-sdk
  • JavaScript/TypeScript: @alibaba-group/opensandbox
  • C#/.NET: Alibaba.OpenSandbox

网络策略

  • Ingress: 入站流量网关,支持多种路由策略
  • Egress: 出站流量控制,可精细化管控沙箱网络访问

集成示例

官方提供了丰富的集成示例:

  • Claude Code 集成
  • Playwright 浏览器自动化
  • VS Code Web 环境
  • 强化学习训练环境

详见 examples/ 目录。


总结

这篇文章我们一起入门了 OpenSandbox,从服务启动、创建沙箱、执行命令、文件操作,到构建 Code Interpreter,核心 API 就这么几个:

  • Sandbox.create() - 创建沙箱
  • sandbox.commands.run() - 执行命令
  • sandbox.files.write_files() / read_file() - 文件操作
  • sandbox.kill() - 清理资源

更复杂的场景(多沙箱管理、自定义健康检查、流式输出)可以参考官方 SDK 文档继续探索。

有问题欢迎在评论区留言,我们下期见!


本文档基于 OpenSandbox v1.0.1编写,官方仓库:https://github.com/alibaba/OpenSandbox

Updated 2026年3月2日