- src/vault-core: no_std 密码学核心(HKDF 派生、AES-256-GCM、两条水位线防回滚) - src/ta-vault / src/ca-vault: TA 薄壳与 selftest 客户端 - build/p1_vault_qemu.sh: QEMU 全链,判据 VAULT_ALL_OK - build/p2_ta_keys_qemu.sh: TA 公钥编进 tee.bin,默认密钥签的被拒 - build/gen_ta_keys.sh: 自建签名密钥 - docs/07-VAULT-TA.md: 设计 + 已验证/未验证清单 - CLAUDE.md 雷区 11-16:user_ta_header、嵌套 workspace、ARCH=arm、SIGPIPE、TA_PUBLIC_KEY、heredoc 变量
171 lines
4.8 KiB
Python
171 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
|
"""CubeSandbox 小助手:创建/复用同一个沙箱,跑命令,后台长任务 + 轮询,收发文件。
|
|
|
|
关键点:创建时必须带 network={"allow_public_traffic": False}(技能硬规范),
|
|
而 traffic token **只在 create 响应里返回一次**,connect 拿不到 —— 所以这里把
|
|
token 和 sandbox id 一起落到本地 JSON,connect 后手工回填,否则命令会 403。
|
|
|
|
用法:
|
|
python3 csbx.py up # 创建(或复用)沙箱
|
|
python3 csbx.py info # 规格 + 剩余寿命
|
|
python3 csbx.py run "cmd" [timeout] # 前台跑
|
|
python3 csbx.py bg NAME "cmd" [total] # 沙箱内 nohup 跑,轮询到结束
|
|
python3 csbx.py log NAME [n] # 看后台任务日志尾部
|
|
python3 csbx.py put LOCAL REMOTE # 上传
|
|
python3 csbx.py get REMOTE LOCAL # 下载
|
|
python3 csbx.py down # 销毁
|
|
"""
|
|
import base64
|
|
import json
|
|
import os
|
|
import sys
|
|
import time
|
|
|
|
os.environ.setdefault("CUBE_API_URL", "http://192.168.1.30:3000")
|
|
os.environ.setdefault("CUBE_PROXY_NODE_IP", "192.168.1.30")
|
|
os.environ.setdefault("CUBE_PROXY_PORT_HTTP", "80")
|
|
|
|
from cubesandbox import Sandbox # noqa: E402
|
|
|
|
STATE = "/tmp/cube_sbx.json"
|
|
TEMPLATE = os.environ.get("CSBX_TEMPLATE", "toolchain")
|
|
|
|
|
|
def _save(sb):
|
|
data = {"id": sb.sandbox_id, "token": sb.traffic_access_token}
|
|
with open(STATE, "w") as f:
|
|
json.dump(data, f)
|
|
|
|
|
|
def _load():
|
|
if not os.path.exists(STATE):
|
|
return None
|
|
try:
|
|
with open(STATE) as f:
|
|
return json.load(f)
|
|
except Exception: # noqa: BLE001
|
|
return None
|
|
|
|
|
|
def _connect(rec):
|
|
sb = Sandbox.connect(rec["id"], timeout=7200)
|
|
if rec.get("token"):
|
|
sb._data["trafficAccessToken"] = rec["token"] # 只在 create 响应里给一次
|
|
return sb
|
|
|
|
|
|
def up():
|
|
rec = _load()
|
|
if rec:
|
|
try:
|
|
sb = _connect(rec)
|
|
print(rec["id"])
|
|
return sb
|
|
except Exception as e: # noqa: BLE001
|
|
print(f"[!] 旧沙箱不可用({e}),重建", file=sys.stderr)
|
|
sb = Sandbox.create(
|
|
template=TEMPLATE,
|
|
timeout=7200,
|
|
network={"allow_public_traffic": False},
|
|
)
|
|
_save(sb)
|
|
print(sb.sandbox_id)
|
|
return sb
|
|
|
|
|
|
def get():
|
|
rec = _load()
|
|
return _connect(rec) if rec else up()
|
|
|
|
|
|
def info():
|
|
sb = get()
|
|
i = sb.get_info()
|
|
keep = {k: i.get(k) for k in ("sandboxID", "templateID", "cpuCount", "memoryMB",
|
|
"startedAt", "endAt", "domain")}
|
|
print(json.dumps(keep, ensure_ascii=False, indent=2))
|
|
print(sb.commands.run("nproc; free -m | head -2; df -h / | tail -1", timeout=60).stdout)
|
|
|
|
|
|
def run(cmd, timeout=300):
|
|
sb = get()
|
|
r = sb.commands.run(cmd, timeout=int(timeout))
|
|
out = r.stdout or ""
|
|
print(out, end="" if out.endswith("\n") else "\n")
|
|
err = getattr(r, "stderr", "") or ""
|
|
if err.strip():
|
|
print("--- stderr ---", file=sys.stderr)
|
|
print(err, file=sys.stderr)
|
|
sys.exit(0 if getattr(r, "exit_code", 0) in (0, None) else 1)
|
|
|
|
|
|
def bg(name, cmd, total=1800, poll=20):
|
|
sb = get()
|
|
sb.commands.run(
|
|
f"rm -f /tmp/{name}.rc; nohup sh -c '{cmd}; echo $? > /tmp/{name}.rc' "
|
|
f"> /tmp/{name}.log 2>&1 & echo started",
|
|
timeout=60,
|
|
)
|
|
t0 = time.time()
|
|
while time.time() - t0 < int(total):
|
|
time.sleep(poll)
|
|
rc = sb.commands.run(f"cat /tmp/{name}.rc 2>/dev/null || echo RUNNING", timeout=30)
|
|
if "RUNNING" not in (rc.stdout or ""):
|
|
print(f"rc={(rc.stdout or '').strip()}")
|
|
print(sb.commands.run(f"tail -30 /tmp/{name}.log", timeout=30).stdout)
|
|
return
|
|
print("TIMEOUT(沙箱还在,可用 log 子命令继续看)")
|
|
|
|
|
|
def log(name, n=60):
|
|
sb = get()
|
|
print(sb.commands.run(f"tail -{n} /tmp/{name}.log", timeout=30).stdout)
|
|
|
|
|
|
def put(local, remote):
|
|
sb = get()
|
|
with open(local, "rb") as f:
|
|
sb.files.write(remote, f.read())
|
|
print(f"put {local} -> {remote}")
|
|
|
|
|
|
def getfile(remote, local):
|
|
sb = get()
|
|
b64 = sb.commands.run(f"base64 -w0 {remote}", timeout=120).stdout.strip()
|
|
with open(local, "wb") as f:
|
|
f.write(base64.b64decode(b64))
|
|
print(f"get {remote} -> {local}")
|
|
|
|
|
|
def down():
|
|
sb = get()
|
|
sb.kill()
|
|
os.remove(STATE)
|
|
print("killed")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
a = sys.argv[1:]
|
|
if not a:
|
|
print(__doc__)
|
|
sys.exit(1)
|
|
cmd = a[0]
|
|
if cmd == "up":
|
|
up()
|
|
elif cmd == "info":
|
|
info()
|
|
elif cmd == "run":
|
|
run(a[1], a[2] if len(a) > 2 else 300)
|
|
elif cmd == "bg":
|
|
bg(a[1], a[2], a[3] if len(a) > 3 else 1800)
|
|
elif cmd == "log":
|
|
log(a[1], int(a[2]) if len(a) > 2 else 60)
|
|
elif cmd == "put":
|
|
put(a[1], a[2])
|
|
elif cmd == "get":
|
|
getfile(a[1], a[2])
|
|
elif cmd == "down":
|
|
down()
|
|
else:
|
|
print(__doc__)
|