当 AI Agent 需要在隔离环境里读写文件时,本地文件系统无法满足安全与可重现的要求。云沙箱提供基于 E2B SDK 的文件系统 API,支持文件读写、目录管理、文件重命名与删除等操作,所有操作均在沙箱隔离文件系统内执行。沙箱提供文件读写、列目录、创建目录、移动和删除等能力。
前提条件
已完成服务授权和 创建 API Key。
已安装 E2B SDK。
安装 SDK
Python:
pip install e2b-code-interpreter==2.8.0TypeScript:
npm i @e2b/code-interpreter@2.6.0配置环境变量
创建 .env 文件并配置以下环境变量:
E2B_API_KEY=e2b_xxx
E2B_API_URL=https://api.cn-beijing.e2b.fc.aliyuncs.com
E2B_DOMAIN=cn-beijing.e2b.fc.aliyuncs.comPython 示例中使用的 E2B_API_KEY 和 E2B_CONN_OPTS 可通过以下辅助代码从环境变量读取:
import os
from dotenv import load_dotenv
load_dotenv()
E2B_API_KEY = os.environ.get("E2B_API_KEY")
E2B_CONN_OPTS = {
"api_url": os.environ.get("E2B_API_URL"),
"domain": os.environ.get("E2B_DOMAIN"),
}TypeScript SDK 使用 import 'dotenv/config' 自动加载 .env 文件,SDK 会自动读取 E2B_DOMAIN。
代码示例
Python
import json
from e2b import Sandbox
sandbox = None
try:
sandbox = Sandbox.create(
api_key=E2B_API_KEY,
timeout=300,
**E2B_CONN_OPTS,
)
sandbox.files.write("/tmp/hello.txt", "Hello, E2B!")
print(sandbox.files.read("/tmp/hello.txt"))
sandbox.files.write(
"/tmp/metadata.json",
json.dumps({"sandbox_id": sandbox.sandbox_id}, indent=2),
)
metadata = json.loads(sandbox.files.read("/tmp/metadata.json"))
print(metadata["sandbox_id"])
sandbox.files.make_dir("/tmp/work/subdir")
sandbox.files.write("/tmp/work/subdir/file.txt", "nested content")
print([item.name for item in sandbox.files.list("/tmp/work/subdir")])
sandbox.files.rename("/tmp/hello.txt", "/tmp/hello-renamed.txt")
sandbox.files.remove("/tmp/hello-renamed.txt")
finally:
if sandbox is not None:
sandbox.kill()TypeScript
import { Sandbox } from 'e2b';
const sandbox = await Sandbox.create({
apiKey: process.env.E2B_API_KEY!,
timeoutMs: 300_000,
});
try {
await sandbox.files.write('/tmp/hello.txt', 'Hello, E2B!');
console.log(await sandbox.files.read('/tmp/hello.txt'));
await sandbox.files.write(
'/tmp/metadata.json',
JSON.stringify({ sandboxId: sandbox.sandboxId }, null, 2)
);
const metadata = JSON.parse(await sandbox.files.read('/tmp/metadata.json'));
console.log(metadata.sandboxId);
await sandbox.files.makeDir('/tmp/work/subdir');
await sandbox.files.write('/tmp/work/subdir/file.txt', 'nested content');
const items = await sandbox.files.list('/tmp/work/subdir');
console.log(items.map(i => i.name));
await sandbox.files.rename('/tmp/hello.txt', '/tmp/hello-renamed.txt');
await sandbox.files.remove('/tmp/hello-renamed.txt');
} finally {
await sandbox.kill();
}建议
临时文件优先放在
/tmp。需要跨沙箱持久化的数据,应使用 OSS、NAS 等外部存储。
大文件传输建议结合上传/下载 URL 或对象存储,避免把大文件塞进控制面请求。
该文章对您有帮助吗?