
OpenAI Codex 런타임 기반의 가볍고 크로스 플랫폼 프로세스 샌드박싱 도구. 파일, 네트워크, 자격 증명 제어 기능으로 모든 명령을 샌드박스 처리합니다.
zerobox용 파이썬 SDK. 파일, 네트워크, 자격 증명 제어 기능으로 모든 명령을 샌드박스 처리합니다.
pip install zerobox
휠을 설치하면 zerobox CLI가 환경의 bin/에 추가되고 파이썬 SDK가 노출됩니다.
CLI 사용법, 시크릿 개념, 전체 플래그 참조, 성능 수치, 플랫폼 지원에 대해서는 메인 README를 참조하세요.
from zerobox import Sandbox
sandbox = Sandbox.create({"allow_write": ["/tmp"]})
print(sandbox.sh("echo hello").text())
명령을 실행하는 세 가지 방법이 있습니다. 각각 .text(), .json(), .output()로 종료하는 ShellCommand를 반환합니다.
name = "world"
sandbox.sh(f"echo hello {name}").text()
data = sandbox.py("import json; print(json.dumps({'sum': 1 + 2}))").json()
sandbox.exec("python3", ["-c", "print('hi')"]).text()
data = sandbox.sh("cat data.json").json()
result = sandbox.sh("exit 42").output()
# CommandOutput(code=42, stdout='', stderr='')
비동기 애플리케이션에서는 AsyncSandbox를 사용하여 샌드박스 처리된 하위 프로세스를 기다리는 동안 이벤트 루프가 차단되지 않도록 하세요. 명령 형태는 Sandbox와 동일하지만 생성과 종료 메서드는 대기(await)합니다.
from zerobox import AsyncSandbox
sandbox = await AsyncSandbox.create({"allow_write": ["/tmp"]})
text = await sandbox.sh("echo hello").text()
data = await sandbox.sh("printf '{\"ok\": true}'").json()
result = await sandbox.exec("python3", ["-c", "print('hi')"]).output()
비동기 명령도 동일한 timeout 옵션을 받습니다:
import subprocess
try:
await sandbox.sh("sleep 60").text(timeout=1.0)
except subprocess.TimeoutExpired:
print("cancelled")
0이 아닌 종료 코드가 발생하면 SandboxCommandError가 발생합니다:
from zerobox import Sandbox, SandboxCommandError
sandbox = Sandbox.create()
try:
sandbox.sh("exit 1").text()
except SandboxCommandError as e:
print(e.code, e.stderr)
샌드박스 처리된 프로세스가 절대 볼 수 없는 API 키를 전달하세요. 프록시는 승인된 호스트에 대해서만 실제 값을 대체합니다.
import os
from zerobox import Sandbox
sandbox = Sandbox.create({
"secrets": {
"OPENAI_API_KEY": {
"value": os.environ["OPENAI_API_KEY"],
"hosts": ["api.openai.com"],
},
"GITHUB_TOKEN": {
"value": os.environ["GITHUB_TOKEN"],
"hosts": ["api.github.com"],
},
},
})
sandbox.sh('curl -H "Authorization: Bearer $OPENAI_API_KEY" https://api.openai.com/v1/models').text()
자리 표시자 대체가 작동하는 방식은 메인 README를 참조하세요.
파일시스템 변경 사항을 기록하고 자동으로 롤백합니다:
sandbox = Sandbox.create({
"allow_write": ["."],
"restore": True,
})
sandbox.sh("npm install").text()
롤백 없이 기록:
sandbox = Sandbox.create({
"allow_write": ["."],
"snapshot": True,
"snapshot_exclude": ["node_modules"],
})
sandbox.sh("npm install").text()
모든 종료 메서드에 timeout(초)을 전달하세요:
import subprocess
try:
sandbox.sh("sleep 60").text(timeout=1.0)
except subprocess.TimeoutExpired:
print("cancelled")
sandbox = Sandbox.create({
"env": {"NODE_ENV": "production"},
"allow_env": ["PATH", "HOME"],
"deny_env": ["AWS_SECRET_ACCESS_KEY"],
})
기본적으로 상속되는 항목과 CLI 동등 옵션은 메인 README를 참조하세요.
Sandbox.create(options)는 SandboxOptions 데이터클래스 또는 일반 dict를 받습니다. 모든 필드는 선택 사항입니다.
알 수 없는 dict 키(예: allow_write 대신 실수로 allowWrite를 사용한 경우)는 생성 시점에 TypeError를 발생시킵니다.
Sandbox.py(code)는 샌드박스 내부의 PATH에 있는 python3를 실행합니다. 활성 인터프리터가 샌드박스의 읽기 가능 루트 밖에 있다면(예: ~/.local/share/uv/ 아래의 uv 관리 Python), 다음으로 대체하세요:
import sys
sandbox = Sandbox.create({"allow_read": [sys.prefix]})
sandbox.exec(sys.executable, ["-c", "print('hi')"]).text()
zerobox)zerobox)Apache-2.0
| 메서드 | 성공 시 | 0이 아닌 종료 코드 시 |
|---|
.text() | stdout을 문자열로 반환 | SandboxCommandError 발생 |
.json() | stdout을 JSON으로 파싱 | SandboxCommandError 발생 |
.output() | CommandOutput(code, stdout, stderr) 반환 | 동일한 형태를 반환하며 예외를 발생시키지 않습니다 |
| 필드 | 타입 | 설명 |
|---|
profile | str | list[str] | 명명된 프로필. 목록은 왼쪽에서 오른쪽으로 병합됩니다. 기본값은 "workspace"입니다. |
allow_read / deny_read | list[str] | 읽기 가능/차단된 경로. |
allow_write / deny_write | list[str] | 쓰기 가능/차단된 경로. |
allow_net | bool | list[str] | True는 모두 허용합니다. 목록은 해당 도메인으로 제한합니다. |
deny_net | list[str] | 차단된 도메인. |
allow_all | bool | 전체 파일시스템 + 네트워크 액세스. |
no_sandbox | bool | 샌드박스를 완전히 비활성화합니다. |
strict_sandbox | bool | 약한 격리로 대체하지 않고 실패합니다. |
cwd | str | 작업 디렉터리. |
env | dict[str, str] | 명시적 환경 변수. |
allow_env | bool | list[str] | 부모 환경 변수를 상속합니다. |
deny_env | list[str] | 차단된 환경 변수. |
snapshot | bool | 파일시스템 변경 사항을 기록합니다. |
restore | bool | 기록하고 종료 후 롤백합니다. snapshot을 포함합니다. |
snapshot_paths / snapshot_exclude | list[str] | 추적 경로 / 제외 패턴. |
secrets | dict[str, SecretConfig] | 호스트별 범위가 있는 시크릿. |
debug | bool | 샌드박스 구성을 stderr로 출력합니다. |