沙盒Skill sandbox

沙盒技能是一种用于安全执行代码的工具,在隔离的Docker容器中运行,提供资源限制、超时保护和容器化隔离。适用于量化交易回测、代码测试、数据分析和DevOps环境,关键词包括沙盒、Docker、代码执行、资源限制、安全隔离、量化回测和容器管理。

DevOps 0 次安装 0 次浏览 更新于 3/9/2026

name: sandbox description: “在资源限制的Docker容器中安全执行代码” emoji: “📦” gates: envs: anyOf: - DOCKER_HOST

沙盒 - 完整API参考

在隔离的Docker容器中安全执行代码,提供资源限制和超时保护。


聊天命令

运行代码

/run python "print('Hello')"                运行Python代码
/run node "console.log('Hi')"               运行JavaScript
/run bash "ls -la"                          运行shell命令
/run ruby "puts 'Hello'"                    运行Ruby代码

带选项

/run python "code" --timeout 30             设置超时(秒)
/run node "code" --memory 512               内存限制(MB)
/run python "code" --file script.py         从文件运行

沙盒管理

/sandbox status                             容器状态
/sandbox images                             可用镜像
/sandbox cleanup                            清理旧容器

TypeScript API 参考

创建沙盒

import { createSandbox } from 'clodds/sandbox';

const sandbox = createSandbox({
  // Docker设置
  dockerHost: process.env.DOCKER_HOST,

  // 默认限制
  defaultTimeoutMs: 30000,
  defaultMemoryMB: 256,
  defaultCpuShares: 512,

  // 清理
  autoCleanup: true,
  maxContainerAgeMs: 3600000,
});

运行代码

// 运行Python
const result = await sandbox.run({
  language: 'python',
  code: `
import math
print(f"Pi is {math.pi}")
  `,
});

console.log(`输出: ${result.stdout}`);
console.log(`退出代码: ${result.exitCode}`);
console.log(`持续时间: ${result.durationMs}ms`);

// 带限制运行
const result = await sandbox.run({
  language: 'node',
  code: `console.log('Hello from Node.js')`,
  timeout: 10000,
  memoryMB: 128,
});

支持的语言

// Python
await sandbox.run({ language: 'python', code: 'print("Hello")' });

// JavaScript (Node.js)
await sandbox.run({ language: 'node', code: 'console.log("Hello")' });

// Bash
await sandbox.run({ language: 'bash', code: 'echo "Hello"' });

// Ruby
await sandbox.run({ language: 'ruby', code: 'puts "Hello"' });

// Go
await sandbox.run({ language: 'go', code: 'package main
import "fmt"
func main() { fmt.Println("Hello") }' });

从文件运行

const result = await sandbox.runFile({
  language: 'python',
  filePath: '/path/to/script.py',
  args: ['--input', 'data.csv'],
});

安装包

// Python包
const result = await sandbox.run({
  language: 'python',
  code: `
import pandas as pd
print(pd.__version__)
  `,
  packages: ['pandas', 'numpy'],
});

// Node包
const result = await sandbox.run({
  language: 'node',
  code: `
const _ = require('lodash');
console.log(_.VERSION);
  `,
  packages: ['lodash'],
});

资源限制

const result = await sandbox.run({
  language: 'python',
  code: 'import time; time.sleep(100)',

  // 限制
  timeout: 5000,        // 5秒超时
  memoryMB: 256,        // 256 MB RAM
  cpuShares: 512,       // CPU份额(默认1024)
  networkDisabled: true, // 无网络访问
});

容器管理

// 获取状态
const status = await sandbox.getStatus();
console.log(`运行中容器: ${status.running}`);
console.log(`总容器数: ${status.total}`);

// 列出可用镜像
const images = await sandbox.listImages();
for (const img of images) {
  console.log(`${img.language}: ${img.image}`);
}

// 清理旧容器
await sandbox.cleanup({
  olderThan: '1h',
  status: 'exited',
});

语言镜像

语言 镜像 版本
python python:3.11-slim 3.11
node node:20-slim 20.x
bash alpine:latest Alpine
ruby ruby:3.2-slim 3.2
go golang:1.21-alpine 1.21

资源限制

资源 默认 最大
超时 30s 300s
内存 256 MB 2048 MB
CPU 512份额 2048份额
磁盘 100 MB 1 GB

安全性

特性 描述
隔离 每次运行在单独容器中
无网络 默认禁用网络
无卷 无主机文件系统访问
只读 文件系统为只读
资源上限 内存和CPU限制
超时 超时后强制终止

使用案例

运行回测

const result = await sandbox.run({
  language: 'python',
  code: backtestCode,
  packages: ['pandas', 'numpy', 'ta'],
  timeout: 60000,
  memoryMB: 512,
});

数据处理

const result = await sandbox.run({
  language: 'python',
  code: `
import json
data = ${JSON.stringify(inputData)}
result = process(data)
print(json.dumps(result))
  `,
});
const output = JSON.parse(result.stdout);

最佳实践

  1. 设置超时 — 防止失控代码
  2. 限制内存 — 避免内存不足
  3. 禁用网络 — 除非需要
  4. 使用轻量镜像 — 更快启动
  5. 定期清理 — 移除旧容器