代码沙箱能力
在沙箱中运行程序和执行编程语言代码
你可以在 Lybic 电脑沙箱中运行你的代码,而不用担心对现实的物理环境产生破坏。本文将介绍lybic沙箱运行代码的能力,以及指导用户在lybic沙箱中安全的运行代码。
你可以将 Lybic 沙箱视为一个完整的操作系统,并在其中编写和执行任意代码。
语言支持
Lybic 沙箱内已经内置了以下编程语言支持:
| 编程语言及版本 | Linux沙箱支持 | Windows 沙箱支持 | 支持的主要启动命令 | 备注 |
|---|---|---|---|---|
| Python 3.12 | ⭕ | ❌ | python python3 python3.12 pip3 uv | 系统包,支持使用python -m venv 创建虚拟环境,可以使用 pip3 install packagename --break-system-packages 将依赖安装至系统 |
| Python 3.13 | ❌ | ⭕ | python pip uv conda-env conda | Anaconda / uv |
| Node.js v24 | ⭕ | ⭕ | node npm npx corepack | |
| Golang 1.25 | ⭕ | ⭕ | go | 在linux沙箱中,CGO_ENABLE=1 |
| Rustlang 1.92 | ⭕ | ⭕ | cargo rustc rustdoc rustfmt rust-analyzer rust-gdb rust-lldb | |
| Gcc 13 | ⭕ | ❌ | gcc g++ | |
| MSVC 14.50(2025) | ❌ | ⭕ | cl link | 需要在 C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools C:\Program Files (x86)\Microsoft Visual Studio\18\BuildTools\VC\Auxiliary\Build\vcvars64.bat 手动激活 |
| Batch Scripts | ❌ | ⭕ | cmd | |
| PowerShell 5.1 | ❌ | ⭕ | powershell | |
| Bash 5.1 | ⭕ | ❌ | bash | |
| Ash 1.20 | ❌ | ⭕ | ash | 通过 Git 提供 |
你可以通过 Lybic SDK 提供的 execSandboxProcess API 在沙箱中运行任意代码,并通过组合输入运行不同编程语言的代码。该 API 支持传入命令行参数、环境变量、标准输入等,并且可以获取标准输出、标准错误输出以及进程退出码。
运行沙箱程序
使用 execSandboxProcess API 可以在沙箱中执行任意程序。以下是各语言 SDK 的示例:
基本用法
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "ls",
"args": ["-la", "/home"],
"workingDirectory": "/home"
}'import asyncio
import base64
from Lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.Lybic.cn/"
)
) as client:
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="/bin/ls",
args=["-la", "/home"],
workingDirectory="/home"
)
print(f"退出代码: {result.exitCode}")
print(f"输出: {base64.b64decode(result.stdoutBase64 or '').decode()}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@Lybic/core'
const Lybic = new LybicClient({
baseUrl: 'https://api.Lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
const result = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'ls',
args: ['-la', '/home'],
workingDirectory: '/home',
})
console.log('退出代码:', result.data?.exitCode)
console.log('输出:', atob(result.data?.stdoutBase64 || ''))package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/Lybic/Lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := Lybic.NewClient(nil)
processDto := Lybic.SandboxProcessRequestDto{
Executable: "/bin/ls",
Args: []string{"-la", "/home"},
}
result, err := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto)
if err != nil {
fmt.Println("执行进程时出错:", err)
return
}
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
fmt.Printf("退出代码: %d\n", result.ExitCode)
fmt.Printf("输出: %s\n", string(stdout))
}请求参数说明:
executable: 要执行的程序路径或命令名(必填)args: 命令行参数数组(可选)workingDirectory: 工作目录(可选)stdinBase64: Base64 编码的标准输入内容(可选)
响应示例:
{
"stdoutBase64": "dG90YWwgNAo...",
"stderrBase64": "",
"exitCode": 0
}响应中的 stdoutBase64 和 stderrBase64 需要进行 Base64 解码才能查看实际输出内容。
执行编程语言代码
Python 代码执行
# 方式 1: 直接执行 Python 代码(通过 stdin)
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "python3",
"stdinBase64": "cHJpbnQoJ0hlbGxvLCBXb3JsZCEnKQ=="
}'
# 方式 2: 执行 Python 文件
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "python3",
"args": ["script.py"],
"workingDirectory": "/home/agent/project"
}'import asyncio
import base64
from Lybic import LybicClient, LybicAuth, dto
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.Lybic.cn/"
)
) as client:
# 方式 1: 通过 stdin 执行 Python 代码
code = "print('Hello, World!')"
stdin_data = base64.b64encode(code.encode()).decode()
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="python3",
stdinBase64=stdin_data
)
print(f"输出: {base64.b64decode(result.stdoutBase64 or '').decode()}")
# 方式 2: 执行 Python 文件
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="python3",
args=["script.py"],
workingDirectory="/home/agent/project"
)
print(f"退出代码: {result.exitCode}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@Lybic/core'
const Lybic = new LybicClient({
baseUrl: 'https://api.Lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// 方式 1: 通过 stdin 执行 Python 代码
const code = "print('Hello, World!')"
const stdinBase64 = btoa(code)
const result1 = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'python3',
args: [],
stdinBase64: stdinBase64,
})
console.log('输出:', atob(result1.data?.stdoutBase64 || ''))
// 方式 2: 执行 Python 文件
const result2 = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'python3',
args: ['script.py'],
workingDirectory: '/home/agent/project',
})
console.log('退出代码:', result2.data?.exitCode)package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/Lybic/Lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := Lybic.NewClient(nil)
// 方式 1: 通过 stdin 执行 Python 代码
code := "print('Hello, World!')"
stdinBase64 := base64.StdEncoding.EncodeToString([]byte(code))
processDto := Lybic.SandboxProcessRequestDto{
Executable: "python3",
Args: []string{},
StdinBase64: &stdinBase64,
}
result, _ := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto)
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
fmt.Printf("输出: %s\n", string(stdout))
// 方式 2: 执行 Python 文件
workDir := "/home/agent/project"
processDto2 := Lybic.SandboxProcessRequestDto{
Executable: "python3",
Args: []string{"script.py"},
WorkingDirectory: &workDir,
}
result2, _ := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto2)
fmt.Printf("退出代码: %d\n", result2.ExitCode)
}Node.js 代码执行
# 执行 JavaScript 代码
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "node",
"args": ["-e", "console.log(\"Hello from Node.js\")"]
}'import asyncio
import base64
from Lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.Lybic.cn/"
)
) as client:
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="node",
args=["-e", "console.log('Hello from Node.js')"]
)
print(f"输出: {base64.b64decode(result.stdoutBase64 or '').decode()}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@Lybic/core'
const Lybic = new LybicClient({
baseUrl: 'https://api.Lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
const result = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'node',
args: ['-e', 'console.log("Hello from Node.js")'],
})
console.log('输出:', atob(result.data?.stdoutBase64 || ''))package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/Lybic/Lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := Lybic.NewClient(nil)
processDto := Lybic.SandboxProcessRequestDto{
Executable: "node",
Args: []string{"-e", "console.log('Hello from Node.js')"},
}
result, _ := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto)
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
fmt.Printf("输出: %s\n", string(stdout))
}Go 代码执行
# 方式 1: 运行 Go 文件
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "go",
"args": ["run", "main.go"],
"workingDirectory": "/home/agent/project"
}'
# 方式 2: 构建并运行
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "go",
"args": ["build", "-o", "app", "main.go"],
"workingDirectory": "/home/agent/project"
}'import asyncio
import base64
from Lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.Lybic.cn/"
)
) as client:
# 运行 Go 文件
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="go",
args=["run", "main.go"],
workingDirectory="/home/agent/project"
)
print(f"输出: {base64.b64decode(result.stdoutBase64 or '').decode()}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@Lybic/core'
const Lybic = new LybicClient({
baseUrl: 'https://api.Lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
// 运行 Go 文件
const result = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'go',
args: ['run', 'main.go'],
workingDirectory: '/home/agent/project',
})
console.log('输出:', atob(result.data?.stdoutBase64 || ''))package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/Lybic/Lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := Lybic.NewClient(nil)
workDir := "/home/agent/project"
processDto := Lybic.SandboxProcessRequestDto{
Executable: "go",
Args: []string{"run", "main.go"},
WorkingDirectory: &workDir,
}
result, _ := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto)
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
fmt.Printf("输出: %s\n", string(stdout))
}Rust 代码执行
# 使用 Cargo 运行项目
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "cargo",
"args": ["run"],
"workingDirectory": "/home/user/rust-project"
}'import asyncio
import base64
from Lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.Lybic.cn/"
)
) as client:
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="cargo",
args=["run"],
workingDirectory="/home/user/rust-project"
)
print(f"输出: {base64.b64decode(result.stdoutBase64 or '').decode()}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@Lybic/core'
const Lybic = new LybicClient({
baseUrl: 'https://api.Lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
const result = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'cargo',
args: ['run'],
workingDirectory: '/home/user/rust-project',
})
console.log('输出:', atob(result.data?.stdoutBase64 || ''))package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/Lybic/Lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := Lybic.NewClient(nil)
workDir := "/home/agent/rust-project"
processDto := Lybic.SandboxProcessRequestDto{
Executable: "cargo",
Args: []string{"run"},
WorkingDirectory: &workDir,
}
result, _ := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto)
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
fmt.Printf("输出: %s\n", string(stdout))
}通过标准输入传递代码
# 通过管道传递 Python 代码
curl -X POST "https://api.Lybic.cn/api/orgs/{orgId}/sandboxes/{sandboxId}/process" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
"executable": "sh",
"args": ["-c","echo \"print('Hello, World!')\" | python"]
}
'import asyncio
import base64
from Lybic import LybicClient, LybicAuth
async def main():
async with LybicClient(
LybicAuth(
org_id="ORG-xxxx",
api_key="lysk-xxxxxxxxxxx",
endpoint="https://api.Lybic.cn/"
)
) as client:
code = 'print("Hello, World!")'
stdin_data = base64.b64encode(code.encode()).decode()
result = await client.sandbox.execute_process(
"SBX-xxxx",
executable="python",
stdinBase64=stdin_data
)
print(f"输出: {base64.b64decode(result.stdoutBase64 or '').decode()}")
if __name__ == "__main__":
asyncio.run(main())import { LybicClient } from '@Lybic/core'
const Lybic = new LybicClient({
baseUrl: 'https://api.Lybic.cn',
orgId: 'ORG-xxxx',
apiKey: 'lysk-your-api-key-here',
})
const code = 'print("Hello, World!")'
const stdinBase64 = btoa(code)
const result = await Lybic.execSandboxProcess('SBX-xxxx', {
executable: 'python',
stdinBase64: stdinBase64,
})
console.log('输出:', atob(result.data?.stdoutBase64 || ''))package main
import (
"context"
"encoding/base64"
"fmt"
"github.com/Lybic/Lybic-sdk-go"
)
func main() {
ctx := context.Background()
client, _ := Lybic.NewClient(nil)
code := `print("Hello, World!")`
stdinBase64 := base64.StdEncoding.EncodeToString([]byte(code))
processDto := Lybic.SandboxProcessRequestDto{
Executable: "python",
StdinBase64: &stdinBase64,
}
result, _ := client.ExecSandboxProcess(ctx, "SBX-xxxx", processDto)
stdout, _ := base64.StdEncoding.DecodeString(result.StdoutBase64)
fmt.Printf("输出: %s\n", string(stdout))
}注意事项
- 所有的标准输入/输出都使用 Base64 编码传输,以确保二进制数据的正确传输
- 进程执行有超时限制,超时后会自动终止
- 工作目录必须在沙箱中存在,否则会执行失败
- 可以通过检查
exitCode来判断程序是否成功执行(0 表示成功)