为什么需要沙箱?
OpenClaw 的 AI 助手可以执行 Shell 命令、读写文件。在某些场景下(如多用户共享、生产环境),你需要限制 AI 的执行权限,防止误操作影响宿主系统。
沙箱模式
在 openclaw.json 中配置:
{
agents: {
defaults: {
sandbox: {
mode: "non-main", // 沙箱模式
perSession: true, // 每个会话独立沙箱
workspaceRoot: "~/.openclaw/sandboxes"
}
}
}
}
模式说明
off:不使用沙箱,AI 直接在宿主系统执行(默认)non-main:除主 agent 外的子 agent 在沙箱中执行all:所有 agent 都在沙箱中执行(最严格)
Docker 沙箱配置
使用 Docker 容器作为沙箱环境:
{
agents: {
defaults: {
sandbox: {
mode: "all",
perSession: true,
workspaceRoot: "~/.openclaw/sandboxes",
docker: {
image: "openclaw-sandbox:bookworm-slim",
workdir: "/workspace",
readOnlyRoot: true,
tmpfs: ["/tmp", "/var/tmp", "/run"],
network: "none",
user: "1000:1000"
},
browser: {
enabled: false
}
}
}
}
}
Docker 参数说明
image:容器镜像名称workdir:容器内的工作目录readOnlyRoot:根文件系统只读,AI 只能写入workdir和tmpfs挂载点tmpfs:临时文件系统挂载点,容器销毁后数据消失network:网络模式,none表示完全断网user:容器内运行的用户 UID:GID,避免以 root 身份执行
安全等级参考
| 配置 | 文件访问 | 网络 | 适用场景 |
|---|---|---|---|
mode: "off" |
完全访问 | 完全访问 | 个人单用户 |
mode: "non-main" |
主 agent 可访问 | 完全访问 | 带子 agent 的工作流 |
mode: "all" + network: "none" |
仅工作目录 | 断网 | 多用户/生产环境 |
工具权限控制
除了沙箱,还可以通过 tools 配置精细控制 AI 可用的工具:
{
tools: {
allow: ["read", "write", "edit", "exec"],
deny: ["browser", "canvas"]
}
}
工具提权
特定用户可以获得更高的工具权限:
{
tools: {
elevated: {
enabled: true,
allowFrom: {
whatsapp: ["+15555550123"],
slack: ["U123"]
}
}
}
}
只有 allowFrom 列表中的用户触发的任务可以使用提权工具。
循环检测
防止 AI 陷入无限工具调用循环:
{
tools: {
loopDetection: {
enabled: true
}
}
}
启用后,OpenClaw 会自动检测重复的工具调用模式并中断。