OpenClaw 是開源 Agent 架構,支援 CLI 編程調用與 Gateway Web UI。本文聚焦真實任務情境:部署 Gateway、Agent CLI、自訂網域名瀏覽器訪問、安全模式與營運、Skill 擴充。鏡像地址、構建 Template、環境與能力約定見 OpenClaw 模板。
前置條件
已完成 SDK 接入(E2B API Key、
api_url、domain)已按 OpenClaw 模板 構建出狀態為
ready的模板,並記錄模板名稱(下文以TEMPLATE_NAME表示)與構建樣本中的OPTS已準備模型 API Key,建立沙箱時通過
envs注入 — 鏡像內不預置國際站:百鍊控制台 擷取 API Key(
sk-開頭)
部署 Gateway
啟動 OpenClaw Gateway,在瀏覽器中與 Agent 對話。以下完整流程:建立 Sandbox → 配置 → 啟動 Gateway → 擷取訪問地址。服務端編程調用見 Agent CLI。
import time
from e2b_code_interpreter import Sandbox
# Gateway 鑒權 Token:自行設定任一字元串,無需從 API 擷取。
# 啟動時傳給 openclaw gateway --token;瀏覽器訪問時通過 URL ?token= 攜帶。
# 官方文檔亦支援 OPENCLAW_APP_TOKEN 環境變數,本質相同。
TOKEN = "my-gateway-token"
PORT = 18789
BAILIAN_API_KEY = "<YOUR-BAILIAN-API-KEY>"
BAILIAN_BASE_URL = "[workspace-id].[region].maas.aliyuncs.com"
BAILIAN_MODEL = "qwen3.8-max"
# 1. 建立 Sandbox
sandbox = Sandbox.create(
template=TEMPLATE_NAME,
timeout=3600,
envs={
"ANTHROPIC_AUTH_TOKEN": BAILIAN_API_KEY,
"ANTHROPIC_BASE_URL": BAILIAN_BASE_URL,
"ANTHROPIC_MODEL": BAILIAN_MODEL,
},
**OPTS,
)
# 註冊百鍊 provider
sandbox.commands.run(
"openclaw onboard --non-interactive --accept-risk --skip-health "
"--auth-choice custom-api-key "
f"--custom-api-key {BAILIAN_API_KEY} "
f"--custom-base-url {BAILIAN_BASE_URL} "
"--custom-compatibility anthropic "
f"--custom-model-id {BAILIAN_MODEL} "
"--custom-provider-id bailian",
timeout=120,
)
# 2. 設定預設模型
sandbox.commands.run(
f"openclaw config set agents.defaults.model.primary bailian/{BAILIAN_MODEL}"
)
# 3. 配置 Control UI(雲沙箱公網訪問必需)
origin = f"https://{sandbox.get_host(PORT)}"
sandbox.commands.run(
f"openclaw config set gateway.controlUi.allowedOrigins '[\"{origin}\"]'"
)
# 4. 啟動 Gateway(後台運行)
sandbox.commands.run(
f"bash -lc 'openclaw config set gateway.controlUi.allowInsecureAuth true && "
f"openclaw config set gateway.controlUi.dangerouslyDisableDeviceAuth true && "
f"openclaw gateway --allow-unconfigured --bind lan --auth token "
f"--token {TOKEN} --port {PORT}'",
background=True,
)
# 5. 等待 Gateway 就緒
for _ in range(45):
probe = sandbox.commands.run(
f'bash -lc \'ss -ltn | grep -q ":{PORT} " && echo ready || echo waiting\''
)
if probe.stdout.strip() == "ready":
break
time.sleep(1)
url = f"https://{sandbox.get_host(PORT)}/?token={TOKEN}"
print(f"Gateway: {url}")Agent CLI
在服務端以編程方式調用 Agent,無需啟動 Gateway。
若已按上文 部署 Gateway 建立了 Sandbox,直接在同一個 sandbox 上執行下方命令即可,無需再次建立。
若僅需 CLI、不啟動 Gateway:
from e2b_code_interpreter import Sandbox
BAILIAN_API_KEY = "<YOUR-BAILIAN-API-KEY>"
BAILIAN_BASE_URL = "[workspace-id].[region].maas.aliyuncs.com"
BAILIAN_MODEL = "qwen3.8-max"
sandbox = Sandbox.create(
template=TEMPLATE_NAME,
timeout=3600,
envs={
"ANTHROPIC_AUTH_TOKEN": BAILIAN_API_KEY,
"ANTHROPIC_BASE_URL": BAILIAN_BASE_URL,
"ANTHROPIC_MODEL": BAILIAN_MODEL,
},
**OPTS,
)
# 註冊百鍊 provider
sandbox.commands.run(
"openclaw onboard --non-interactive --accept-risk --skip-health "
"--auth-choice custom-api-key "
f"--custom-api-key {BAILIAN_API_KEY} "
f"--custom-base-url {BAILIAN_BASE_URL} "
"--custom-compatibility anthropic "
f"--custom-model-id {BAILIAN_MODEL} "
"--custom-provider-id bailian",
timeout=120,
)
result = sandbox.commands.run(
f'openclaw agent --local --agent main --model bailian/{BAILIAN_MODEL} '
'-m "What is 2+2? Reply with just the number."',
timeout=120,
)
print(result.stdout)瀏覽器訪問(雲沙箱)
要在瀏覽器中開啟雲沙箱的 Gateway Control UI,須先綁定自訂網域名。預設平台網域名稱(*.sandbox.aliyuncs.com)會觸發下載而非開啟頁面;綁定自訂網域名後可正常訪問。控制台添加網域名稱、DNS 解析、HTTPS 認證及 SDK 配置的完整步驟,見 雲沙箱自訂網域名。
配置自訂網域名
第一步:控制台配置。 在Function Compute控制台為雲沙箱綁定自訂網域名,配置認證與 DNS(api.<你的自訂網域名> / *.<你的自訂網域名>)。
第二步:SDK 改 OPTS。 將 OpenClaw 模板 中的預設 OPTS:
OPTS = {
"api_key": "<你的 E2B API Key>",
"api_url": "https://api.cn-beijing.sandbox.aliyuncs.com",
"domain": "cn-beijing.sandbox.aliyuncs.com",
}替換為與控制台一致的自訂網域名(api_key 須為綁定該自訂網域名的同一帳號下的 Key):
OPTS = {
"api_key": "<你的 E2B API Key>",
"api_url": "https://api.<你的自訂網域名>",
"domain": "<你的自訂網域名>",
}第三步:全流程傳入 OPTS。Template.build(..., **OPTS)、Sandbox.create(..., **OPTS) 及文檔中其他 SDK 調用均使用上述 OPTS,無需額外參數。
完成後 sandbox.get_host(PORT) 將返回 {PORT}-sbx-{sandbox_id}.<你的自訂網域名>;Gateway 的 allowedOrigins、瀏覽器地址欄與下文 curl 中的 <host> 均使用該地址。
開啟 Control UI
完成自訂網域名配置並 部署 Gateway 後,公網訪問還需鑒權:
鑒權 | 來源 | 作用 | 傳遞方式 |
Gateway Token | 代碼中自行設定的 | OpenClaw Control UI | URL 參數 |
運行上文指令碼,記錄輸出的
GatewayURL開啟 Gateway URL(URL 中已含
?token=)
可用 curl 先驗證:
curl -sI "https://<host>/?token=<Gateway Token>"期望響應含 200;回應標頭中的 Content-Type 為 text/html 即表示 Gateway 正常。
若出現“瀏覽器來源不被允許”,確認 allowedOrigins 與地址欄來源完全一致(https://{sandbox.get_host(PORT)},無尾部 /),修改後 重啟 Gateway。
安全模式
測試階段可關閉裝置配對(上文已設定 dangerouslyDisableDeviceAuth true)。若啟用安全模式,開啟 URL 後需批准待配對裝置:
import json
for _ in range(30):
try:
res = sandbox.commands.run(
f"openclaw devices list --json --url ws://127.0.0.1:{PORT} --token {TOKEN}"
)
data = json.loads(res.stdout)
if data.get("pending"):
rid = data["pending"][0]["requestId"]
sandbox.commands.run(
f"openclaw devices approve {rid} --token {TOKEN} "
f"--url ws://127.0.0.1:{PORT}"
)
print(f"Device approved: {rid}")
break
except Exception:
pass
time.sleep(2)重啟 Gateway
修改模型或配置後,在當前 Sandbox 中執行:
origin = f"https://{sandbox.get_host(PORT)}"
sandbox.commands.run(
f"openclaw config set gateway.controlUi.allowedOrigins '[\"{origin}\"]'"
)
sandbox.commands.run(
"""bash -lc 'for p in "[o]penclaw gateway" "[o]penclaw-gateway"; do
for pid in $(pgrep -f "$p" || true); do kill "$pid" 2>/dev/null || true; done
done'"""
)
time.sleep(1)
sandbox.commands.run(
f"openclaw gateway --allow-unconfigured --bind lan --auth token "
f"--token {TOKEN} --port {PORT}",
background=True,
)
for _ in range(45):
probe = sandbox.commands.run(
f'bash -lc \'ss -ltn | grep -q ":{PORT} " && echo ready || echo waiting\''
)
if probe.stdout.strip() == "ready":
break
time.sleep(1)關閉不安全配置
sandbox.commands.run(
"bash -lc 'openclaw config set gateway.controlUi.allowInsecureAuth false && "
"openclaw config set gateway.controlUi.dangerouslyDisableDeviceAuth false'"
)
sandbox.commands.run(
"""bash -lc 'for p in "[o]penclaw gateway" "[o]penclaw-gateway"; do
for pid in $(pgrep -f "$p" || true); do kill "$pid" 2>/dev/null || true; done
done'"""
)
sandbox.commands.run(
f"openclaw gateway --allow-unconfigured --bind lan --auth token "
f"--token {TOKEN} --port {PORT}",
background=True,
)使用 Skill 擴充能力
OpenClaw 通過 Skill(目錄 + SKILL.md)擴充 Agent 能力,Gateway 與 Agent CLI 均可使用。詳見 OpenClaw Skills。
以下樣本假設已按上文建立 sandbox(Gateway 或 Agent CLI 均可)。鏡像不預裝自訂 Skill;可用 openclaw skills list 查看已載入 Skill(含 bundled)。路徑約定見 OpenClaw 模板。
以下以阿里雲百鍊為例(BAILIAN_MODEL 見上文)。
寫入 Managed Skill:
sandbox.files.write(
"/home/user/.openclaw/skills/summarize-changes/SKILL.md",
"""---
name: summarize-changes
description: Summarizes uncommitted changes and flags risks. Use when reviewing diffs or writing commit messages.
user-invocable: true
---
## Instructions
1. Run `git diff HEAD` and summarize changes in 2–3 bullets.
2. List risks such as missing error handling or hardcoded values.
3. If the diff is empty, say there are no uncommitted changes.
""",
)
# 確認已出現在列表中
print(sandbox.commands.run("openclaw skills list").stdout)
result = sandbox.commands.run(
f'openclaw agent --local --agent main --model bailian/{BAILIAN_MODEL} '
'--message "/summarize-changes"',
timeout=0,
)
print(result.stdout)寫入 Workspace Skill:
sandbox.files.write(
"/home/user/.openclaw/workspace/skills/api-conventions/SKILL.md",
"""---
name: api-conventions
description: API design conventions. Use when adding or changing HTTP endpoints or /healthz.
user-invocable: true
---
When writing API endpoints:
- Use RESTful naming
- Return consistent error formats
- Include request validation
""",
)
result = sandbox.commands.run(
f'openclaw agent --local --agent main --model bailian/{BAILIAN_MODEL} '
'--message "/api-conventions Add a /healthz endpoint"',
timeout=0,
)
print(result.stdout)從本機上傳多檔案 Skill 目錄:
若 Skill 含 scripts/、references/ 等附屬檔案,可以用 files.write_files 一次批量寫入:
from pathlib import Path
def upload_skill_dir(sandbox, local_dir: str, remote_root: str) -> None:
local = Path(local_dir).resolve()
entries = []
for path in local.rglob("*"):
if path.is_file():
rel = path.relative_to(local).as_posix()
entries.append({
"path": f"{remote_root.rstrip('/')}/{rel}",
"data": path.read_bytes(),
})
sandbox.files.write_files(entries)
# 本機目錄結構樣本:
# ./my-skills/echo-marker/SKILL.md
# ./my-skills/echo-marker/scripts/marker.txt
upload_skill_dir(
sandbox,
"./my-skills/echo-marker",
"/home/user/.openclaw/skills/echo-marker", # Managed;Workspace 則用 workspace/skills/...
)
print(sandbox.commands.run("openclaw skills list").stdout)
result = sandbox.commands.run(
f'openclaw agent --local --agent main --model bailian/{BAILIAN_MODEL} '
'--message "/echo-marker"',
timeout=0,
)
print(result.stdout)關於 Template.copy:暫不支援Template.build時用.copy("local-dir", "/home/user/.openclaw/skills/...")預置檔案。自訂 Skill 請用上方運行時files.write/files.write_files。
從 ClawHub 安裝(可選):
沙箱預設具備公網出站,可直接搜尋 / 安裝社區 Skill(瀏覽 clawhub.ai):
# 搜尋
result = sandbox.commands.run("openclaw skills search calendar", timeout=120)
print(result.stdout)
# 安裝
sandbox.commands.run("openclaw skills install ws-calendar", timeout=180)參數說明
步驟 | 說明 |
| Gateway 監聽 |
| 通過 URL 參數 |
瀏覽器開啟 URL | Gateway 提供 UI,瀏覽器建立 WebSocket |
| 安全模式下需先批准裝置 |
| 批准瀏覽器裝置指紋 |
瀏覽器重連 | WebSocket 串連成功,UI 可用 |
清理
任務完成後釋放資源:
sandbox.kill()計費說明
Sandbox 按 CPU、記憶體規格與運行時間長度計費;模型 API 呼叫費用由模型服務單獨結算。詳見 計費概述。
常見問題
現象 | 處理 |
Agent 無響應 | 確認 |
Gateway 瀏覽器打不開 | 確認 Gateway URL 含 |
瀏覽器觸發下載 | 須綁定自訂網域名,見 雲沙箱自訂網域名 與 瀏覽器訪問(雲沙箱Agent Sandbox極速版) |
| API Key 與雲沙箱自訂網域名須為同一帳號 |
來源不被允許 |
|
構建失敗 | 確認 |
其他 SDK / 構建問題 |
相關文檔
OpenClaw 模板:鏡像地址、構建 Template、Gateway 參數、環境概覽、Skill 能力約定