沙箱概述
OpenClaw 的沙箱系统为 AI 生成的代码提供安全的执行环境。代码在隔离的容器中运行,防止恶意代码影响宿主系统。
启用沙箱
openclaw sandbox enable
前置要求:
- Docker(推荐)或 gVisor
- 足够的系统资源
沙箱状态
openclaw sandbox status
Sandbox Status:
Engine: Docker
Status: Running
Container: openclaw-sandbox
Runtime: node, python, bash
Memory limit: 256MB
CPU limit: 1 core
Timeout: 30s
Executions today: 45
Errors today: 2
配置沙箱
{
"sandbox": {
"enabled": true,
"engine": "docker",
"image": "openclaw/sandbox:latest",
"limits": {
"memory": "256m",
"cpu": "1.0",
"timeout": 30000,
"maxOutputSize": "1mb",
"maxFileSize": "10mb",
"networkAccess": false
},
"runtimes": ["node", "python", "bash"],
"blockedModules": ["os", "subprocess", "shutil"],
"tempDir": "/tmp/openclaw-sandbox"
}
}
手动执行代码
# 执行 Python
openclaw sandbox exec --lang python "print('Hello, World!')"
# 执行 JavaScript
openclaw sandbox exec --lang node "console.log('Hello!')"
# 从文件执行
openclaw sandbox exec --lang python --file script.py
管理沙箱实例
# 重启沙箱容器
openclaw sandbox restart
# 停止沙箱
openclaw sandbox stop
# 清理临时文件
openclaw sandbox cleanup
# 更新沙箱镜像
openclaw sandbox update
运行时管理
# 查看可用运行时
openclaw sandbox runtimes
# 添加运行时
openclaw sandbox add-runtime ruby
# 移除运行时
openclaw sandbox remove-runtime ruby
Available Runtimes:
python 3.11 ✓ Installed
node 20.11 ✓ Installed
bash 5.2 ✓ Installed
ruby 3.3 ✗ Not installed
go 1.22 ✗ Not installed
安全配置
网络隔离
{
"sandbox": {
"limits": {
"networkAccess": false
}
}
}
默认禁止网络访问。如果需要允许特定请求:
{
"sandbox": {
"network": {
"enabled": true,
"allowedDomains": ["api.example.com"],
"blockedPorts": [22, 25, 3306]
}
}
}
文件系统限制
{
"sandbox": {
"filesystem": {
"readOnly": false,
"allowedPaths": ["/tmp"],
"maxFiles": 10,
"maxFileSize": "10mb"
}
}
}
禁用危险操作
{
"sandbox": {
"blockedSyscalls": ["fork", "exec", "socket"],
"blockedModules": {
"python": ["os", "subprocess", "socket", "ctypes"],
"node": ["child_process", "fs", "net", "cluster"]
}
}
}
查看执行日志
openclaw sandbox logs
openclaw sandbox logs --last 20
openclaw sandbox logs --errors
Execution Log:
[2026-03-19 10:30:01] python ✓ Success 150ms user001
[2026-03-19 10:28:15] node ✓ Success 80ms user002
[2026-03-19 10:25:33] python ✗ Timeout 30000ms user003
[2026-03-19 10:20:01] bash ✗ Blocked 0ms user001 (os module)
资源监控
openclaw sandbox monitor
Sandbox Resource Usage:
Memory: 45MB / 256MB (17%)
CPU: 12% average
Disk: 150MB temp files
Active executions: 2
Queue: 0
为频道启用代码执行
{
"channels": {
"discord-dev": {
"tools": ["code_exec"],
"sandbox": {
"allowedLanguages": ["python", "node"],
"maxExecutionsPerMinute": 5
}
}
}
}
总结
沙箱系统是 OpenClaw 代码执行功能的安全基础。通过严格的资源限制、网络隔离和模块黑名单,确保 AI 生成的代码不会对宿主系统造成危害。建议生产环境始终使用 Docker 引擎运行沙箱。