0

ch-13

约 15000 字DraftOpenClaw Book

第 13 章 · CLI 命令大全与工作流自动化

OpenClaw 的 CLI 不只是一个管理工具——它是一个完整的自动化接口。你能在聊天中做的事,CLI 都能做;很多 CLI 能做的事,聊天反而做不了。

本章你将学到:

  • 理解 CLI 命令的体系架构和设计哲学
  • 掌握所有核心命令的使用方法
  • 能用 CLI 构建自动化运维工作流
  • 理解 CLI 幕后的 Gateway RPC 交互

13.1 CLI 设计哲学

OpenClaw 的 CLI 遵循一个简单原则:CLI 能做一切 GUI 能做的事,外加 GUI 做不了的事

┌─────────────────────────────────────────────────────┐
│                    CLI 能力层                         │
├─────────────────────────────────────────────────────┤
│                                                     │
│  第三层:自动化(脚本、CI/CD、Cron 集成)              │
│  ├── 批量操作                                        │
│  ├── 非交互式配置                                     │
│  └── 机器可读输出(--json)                            │
│                                                     │
│  第二层:运维(Gateway 管理、调试、诊断)               │
│  ├── 服务生命周期                                     │
│  ├── 健康检查和探针                                   │
│  └── 日志和事件追踪                                   │
│                                                     │
│  第一层:交互(配置向导、通道管理、模型切换)            │
│  ├── onboard / configure 向导                        │
│  ├── channels add/remove                            │
│  └── models set                                     │
│                                                     │
└─────────────────────────────────────────────────────┘

13.1.1 全局标志

所有 openclaw 命令都支持以下全局标志:

--dev         # 隔离到 ~/.openclaw-dev,偏移默认端口(开发环境)
--profile <n> # 隔离到 ~/.openclaw-<name>(多 Gateway 场景)
--no-color    # 禁用 ANSI 颜色
--json        # 机器可读 JSON 输出(大多数子命令支持)
-V / --version  # 打印版本号

--dev--profile 是多环境隔离的核心工具。--dev 专门用于开发(自动偏移端口避免冲突),--profile 用于命名隔离(如 --profile test--profile rescue)。

13.1.2 输出约定

  • TTY 环境:彩色输出 + 进度指示器 + OSC-8 可点击链接
  • 非 TTY / --json:纯文本或 JSON,适合脚本处理
  • --no-color:禁用 ANSI 样式(也尊重 NO_COLOR=1 环境变量)

13.2 命令全景图

OpenClaw 的 CLI 命令按功能域组织:

openclaw
├── 生命周期
│   ├── setup / onboard / configure  ← 初始化和配置
│   ├── doctor                       ← 健康检查和修复
│   ├── reset / uninstall            ← 重置和卸载
│   └── update                       ← 版本更新
│
├── Gateway
│   ├── gateway run                   ← 前台运行
│   ├── gateway install/start/stop    ← 服务管理
│   ├── gateway status/probe/health   ← 状态诊断
│   ├── gateway discover              ← Bonjour 发现
│   └── gateway call <method>         ← 底层 RPC
│
├── 配置
│   ├── config get/set/unset         ← 读写配置
│   ├── config validate               ← 校验配置
│   └── config schema                 ← 输出 JSON Schema
│
├── 通道
│   ├── channels list/status/logs     ← 查看状态
│   ├── channels add/remove           ← 增删账户
│   └── channels login/logout         ← 登录登出
│
├── 模型
│   ├── models status/list            ← 查看模型
│   ├── models set / set-image        ← 切换模型
│   ├── models auth add/setup-token   ← 认证管理
│   └── models scan                   ← 自动发现模型
│
├── Agent
│   ├── agents list/add/delete        ← Agent 管理
│   ├── agents bind/unbind            ← 路由绑定
│   └── agent --message "..."         ← 执行一轮对话
│
├── 会话
│   ├── sessions                      ← 列出会话
│   └── sessions cleanup              ← 清理过期会话
│
├── 消息
│   ├── message send/poll/react       ← 发送消息
│   ├── message thread                ← 线程管理
│   └── message emoji/sticker         ← 表情管理
│
├── 自动化
│   ├── cron add/edit/rm/run          ← 定时任务
│   ├── hooks list/enable/disable     ← 钩子管理
│   └── webhooks gmail setup/run      ← Webhook
│
├── Node
│   ├── nodes status/invoke           ← 管理 Node
│   ├── nodes camera/canvas/screen    ← 节点能力
│   ├── devices approve/reject        ← 设备配对
│   └── node run/install              ← 无头 Node 服务
│
├── 工具
│   ├── memory search/index           ← 记忆搜索
│   ├── skills list/install           ← 技能管理
│   ├── plugins list/install          ← 插件管理
│   ├── browser <action>              ← 浏览器控制
│   ├── sandbox list/explain          ← 沙盒管理
│   └── approvals get/set             ← 命令审批
│
├── 安全
│   ├── security audit                ← 安全审计
│   ├── secrets audit/reload          ← 凭证管理
│   └── pairing approve               ← 配对管理
│
└── 调试
    ├── status --deep                 ← 深度诊断
    ├── logs --follow                 ← 实时日志
    └── tui                           ← 终端 UI

13.3 生命周期管理

13.3.1 安装和初始化

# 完整安装 + 向导
openclaw onboard --install-daemon

# 非交互式安装(适合脚本和 CI)
openclaw onboard --non-interactive \
  --auth-choice token \
  --token $ANTHROPIC_API_KEY \
  --gateway-port 18789 \
  --gateway-auth token \
  --gateway-token $GATEWAY_TOKEN \
  --install-daemon

onboard 是"一站式"命令——它初始化配置、创建工作空间、安装 Gateway 服务。setup 只做初始化,不运行向导。

13.3.2 健康检查和修复

# 快速检查
openclaw doctor

# 深度扫描(包括系统级服务)
openclaw doctor --deep

# 无交互修复
openclaw doctor --yes --non-interactive

doctor 是你的"万能修车工具"——它检查配置、Gateway 连接、遗留服务、工作空间状态,并给出修复建议。

13.3.3 Dashboard

# 打开 Dashboard(自动在浏览器中打开)
openclaw dashboard

# 只打印 URL,不打开浏览器
openclaw dashboard --no-open

13.3.4 备份

# 创建备份
openclaw backup create

# 验证备份
openclaw backup verify

13.3.5 重置和卸载

# 重置(分级,安全的先)
openclaw reset --scope config              # 只重置配置
openclaw reset --scope config+creds+sessions # 配置 + 凭证 + 会话
openclaw reset --scope full                 # 全部(包括工作空间)

# 预览会删除什么
openclaw reset --scope full --dry-run

# 完全卸载
openclaw uninstall --all --yes

13.4 Gateway 管理

13.4.1 运行 Gateway

# 前台运行(开发/调试用)
openclaw gateway run

# 常用选项
openclaw gateway run --port 18789 --verbose
openclaw gateway run --bind tailnet --tailscale serve
openclaw gateway run --dev           # 开发模式(自动创建配置)

# 非交互式启动(跳过 gateway.mode=local 检查)
openclaw gateway run --allow-unconfigured

安全守卫:如果不配置认证就尝试绑定到非 loopback 地址,Gateway 会拒绝启动。这是防止"裸奔"的硬性限制。

13.4.2 服务管理

openclaw gateway install    # 安装为系统服务
openclaw gateway start      # 启动
openclaw gateway stop       # 停止
openclaw gateway restart    # 重启
openclaw gateway status     # 查看状态(含 RPC 探针)
openclaw gateway uninstall  # 卸载服务

gateway status 是最常用的诊断命令:

# 基本状态
openclaw gateway status

# 深度扫描(包括系统级服务)
openclaw gateway status --deep

# 要求 RPC 必须成功(脚本中用)
openclaw gateway status --require-rpc

# 跳过 RPC 探针(只看服务状态)
openclaw gateway status --no-probe

# 机器可读
openclaw gateway status --json

13.4.3 Gateway 探针

gateway probe 是"调试一切"的命令——它同时探测配置的远程 Gateway 和 localhost:

openclaw gateway probe

# 通过 SSH 探测远程 Gateway(macOS App 远程模式的 CLI 等效)
openclaw gateway probe --ssh user@gateway-host

# 自动选择已发现的 Gateway 作为 SSH 目标
openclaw gateway probe --ssh-auto

输出解读:

  • Reachable: yes — 至少一个目标接受 WebSocket 连接
  • RPC: ok — 详细 RPC 调用(health/status/config.get)也成功
  • RPC: limited — 连接成功但权限不足(缺少 operator.read scope)
  • 退出码非零 — 没有任何目标可达

13.4.4 Gateway 发现

# 发现局域网内的 Gateway(Bonjour/mDNS)
openclaw gateway discover

# 超时 4 秒
openclaw gateway discover --timeout 4000

# 只输出 WebSocket URL
openclaw gateway discover --json | jq '.beacons[].wsUrl'

13.4.5 底层 RPC

当内置命令不够用时,直接调用 Gateway RPC:

# 获取状态
openclaw gateway call status

# 获取最近 60 秒的日志
openclaw gateway call logs.tail --params '{"sinceMs": 60000}'

# 应用配置变更
openclaw gateway call config.apply

# 合并部分配置更新
openclaw gateway call config.patch --params '{"agents":{"defaults":{"model":{"primary":"openai/gpt-4o"}}}}'

13.5 配置管理

openclaw config 是非交互式配置操作的核心——所有你能通过 openclaw configure 向导做的事,都能用 config 命令一行搞定。

13.5.1 读取配置

# 打印当前配置文件路径
openclaw config file

# 获取配置值(支持点号路径和数组索引)
openclaw config get agents.defaults.workspace
openclaw config get agents.list[0].id
openclaw config get agents.list

# 输出 JSON Schema
openclaw config schema > openclaw.schema.json

13.5.2 设置配置

config set 支持四种赋值模式:

1. 值模式(最常用):

openclaw config set agents.defaults.heartbeat.every "2h"
openclaw config set gateway.port 19001 --strict-json
openclaw config set channels.whatsapp.groups '["*"]' --strict-json

值会被尝试解析为 JSON5;如果解析失败,按字符串处理。--strict-json 强制要求 JSON5 格式。

2. SecretRef 构建器模式(推荐用于凭证):

openclaw config set channels.discord.token \
  --ref-provider default \
  --ref-source env \
  --ref-id DISCORD_BOT_TOKEN

这比直接写明文 Token 安全得多——配置文件中只存储引用,不存储实际值。

3. Provider 构建器模式(用于 secrets providers):

openclaw config set secrets.providers.vault \
  --provider-source exec \
  --provider-command /usr/local/bin/openclaw-vault \
  --provider-arg read \
  --provider-arg openai/api-key \
  --provider-json-only \
  --provider-pass-env VAULT_TOKEN \
  --provider-trusted-dir /usr/local/bin \
  --provider-timeout-ms 5000

4. 批量模式(适合一次性设置多个值):

openclaw config set --batch-json '[
  {
    "path": "secrets.providers.default",
    "provider": { "source": "env" }
  },
  {
    "path": "channels.discord.token",
    "ref": { "source": "env", "provider": "default", "id": "DISCORD_BOT_TOKEN" }
  }
]'

13.5.3 Dry Run(预览变更)

修改配置前,先用 --dry-run 验证:

openclaw config set channels.discord.token \
  --ref-provider default \
  --ref-source env \
  --ref-id DISCORD_BOT_TOKEN \
  --dry-run

# 机器可读输出
openclaw config set channels.discord.token \
  --ref-provider default \
  --ref-source env \
  --ref-id DISCORD_BOT_TOKEN \
  --dry-run --json

Dry run 会检查:

  • 配置 schema 是否合法
  • SecretRef 是否可解析(env 变量是否存在、文件是否可读等)

默认跳过 exec 类型的 SecretRef 检查(避免执行外部命令)。如果需要,加 --allow-exec

13.5.4 删除和验证

# 删除配置项
openclaw config unset plugins.entries.brave.config.webSearch.apiKey

# 验证当前配置
openclaw config validate
openclaw config validate --json

13.6 通道管理

13.6.1 查看通道状态

# 列出所有已配置的通道
openclaw channels list

# 检查通道健康状态
openclaw channels status

# 带深度探针检查
openclaw channels status --probe

# 查看通道能力
openclaw channels capabilities
openclaw channels capabilities --channel discord --target channel:123

# 查看通道日志
openclaw channels logs --channel all
openclaw channels logs --channel telegram --lines 50

13.6.2 增删通道账户

# 交互式添加(向导模式)
openclaw channels add

# 非交互式添加
openclaw channels add --channel telegram --token $TELEGRAM_BOT_TOKEN

# 添加命名账户
openclaw channels add --channel telegram --account alerts --name "Alerts Bot" --token $TOKEN

# 删除通道
openclaw channels remove --channel discord --account work --delete

13.6.3 登录和登出

# WhatsApp Web 登录(会显示 QR 码)
openclaw channels login --channel whatsapp

# 登出
openclaw channels logout --channel whatsapp

13.6.4 名称解析

将通道/用户名解析为 ID:

openclaw channels resolve --channel slack "#general" "@jane"
openclaw channels resolve --channel discord "My Server/#support" "@someone"

13.7 模型管理

13.7.1 查看模型状态

# 当前模型配置
openclaw models status

# 机器可读
openclaw models status --json

# 检查凭证是否过期
# 退出码:0=正常, 1=已过期/缺失, 2=即将过期
openclaw models status --check

# 实时探测(实际调用模型 API,会消耗 Token)
openclaw models status --probe

13.7.2 列出和切换模型

# 列出可用模型
openclaw models list
openclaw models list --provider anthropic
openclaw models list --all

# 切换主模型
openclaw models set anthropic/claude-sonnet-4-6

# 切换图像模型
openclaw models set-image anthropic/claude-sonnet-4-6

13.7.3 备选模型管理

# 备选模型列表
openclaw models fallbacks list

# 添加备选
openclaw models fallbacks add openai/gpt-4o-mini

# 删除备选
openclaw models fallbacks remove openai/gpt-4o-mini

# 清空备选
openclaw models fallbacks clear

13.7.4 模型别名

openclaw models aliases list
openclaw models aliases add my-model anthropic/claude-opus-4-6
openclaw models aliases remove my-model

13.7.5 模型认证

# 交互式添加认证
openclaw models auth add

# 使用 Anthropic setup-token
openclaw models auth setup-token --provider anthropic

# 粘贴 Token
openclaw models auth paste-token --provider anthropic --profile-id my-key --expires-in 365d

# 认证优先级管理
openclaw models auth order get --provider anthropic
openclaw models auth order set --provider anthropic my-key another-key

13.7.6 模型扫描

models scan 自动探测可用的模型(通过已配置的 Provider):

# 扫描并自动设为默认
openclaw models scan --set-default --yes

# 扫描并设为图像模型
openclaw models scan --set-image --yes

# 只扫描特定 Provider
openclaw models scan --provider anthropic

13.8 Agent 管理

13.8.1 列出和创建 Agent

# 列出所有 Agent
openclaw agents list
openclaw agents list --bindings  # 包含路由绑定信息

# 创建新 Agent(交互式)
openclaw agents add

# 创建新 Agent(非交互式)
openclaw agents add ops \
  --workspace ~/.openclaw/agents/ops/workspace \
  --model anthropic/claude-sonnet-4-6 \
  --bind telegram:ops \
  --bind discord:ops

# 删除 Agent
openclaw agents delete ops --force

13.8.2 路由绑定

# 查看路由绑定
openclaw agents bindings
openclaw agents bindings --agent ops

# 添加绑定
openclaw agents bind --agent ops --bind telegram:ops --bind discord:ops

# 移除绑定
openclaw agents unbind --agent ops --bind telegram:ops

# 移除所有绑定
openclaw agents unbind --agent ops --all

13.8.3 执行 Agent 对话

# 执行一轮对话
openclaw agent --message "总结今天的日志"

# 指定 Agent
openclaw agent --agent ops --message "生成报告"

# 发送到特定通道
openclaw agent --to +15555550123 --message "状态更新" --deliver

# 指定会话和思考模式
openclaw agent --session-id 1234 --message "总结收件箱" --thinking medium

# 本地嵌入模式(不需要 Gateway)
openclaw agent --local --message "快速测试" --model anthropic/claude-sonnet-4-6

--deliver 让 Agent 的回复通过通道发送出去(而不是只返回到 CLI)。

13.9 消息系统

openclaw message 是统一的出站消息接口——支持发送、投票、表情、线程、频道管理等一系列操作。

13.9.1 发送消息

# 发送文本消息
openclaw message send --target +15555550123 --message "Hello"

# 发送到 Discord 频道
openclaw message send --target "#general" --channel discord --message "公告"

# 创建投票
openclaw message poll --channel discord --target channel:123 \
  --poll-question "午餐吃什么?" \
  --poll-option "火锅" \
  --poll-option "烧烤" \
  --poll-option "面食"

13.9.2 更多消息操作

# 消息反应
openclaw message react --target "<message-id>" --emoji "👍"

# 编辑消息
openclaw message edit --target "<message-id>" --message "修正后的内容"

# 删除消息
openclaw message delete --target "<message-id>"

# 置顶/取消置顶
openclaw message pin --target "<message-id>"
openclaw message unpin --target "<message-id>"

# 搜索消息
openclaw message search --channel discord --query "关键词"

# 线程管理
openclaw message thread create --target "<message-id>" --message "回复内容"
openclaw message thread list --target "<message-id>"

13.9.3 频道管理

# 频道信息
openclaw message channel info --target "#general" --channel discord

# 列出频道
openclaw message channel list --channel discord

# 成员信息
openclaw message member info --target "@user" --channel discord

13.10 会话管理

13.10.1 查看会话

# 列出默认 Agent 的会话
openclaw sessions

# 指定 Agent
openclaw sessions --agent work

# 所有 Agent 的会话
openclaw sessions --all-agents

# 只看最近 2 小时活跃的会话
openclaw sessions --active 120

# 机器可读
openclaw sessions --json

13.10.2 会话清理

# 预览会清理什么
openclaw sessions cleanup --dry-run

# 执行清理
openclaw sessions cleanup --enforce

# 指定 Agent
openclaw sessions cleanup --agent work --dry-run

# 保护活跃会话不被清理
openclaw sessions cleanup --enforce --active-key "agent:main:telegram:direct:123"

# 机器可读
openclaw sessions cleanup --all-agents --dry-run --json

13.11 自动化命令

13.11.1 Cron 定时任务

# 查看 Cron 状态
openclaw cron status

# 列出所有任务
openclaw cron list
openclaw cron list --all  # 包括禁用的

# 创建定时任务(每天 8:00 发送天气提醒)
openclaw cron add --name "morning-weather" \
  --at "0 8 * * *" \
  --message "告诉我今天的天气和日程"

# 创建周期性任务(每 30 分钟)
openclaw cron add --name "status-check" \
  --every "30m" \
  --system-event "check system status"

# 编辑任务
openclaw cron edit <job-id> --message "新的消息内容"

# 手动运行一次
openclaw cron run <job-id>

# 强制运行(忽略 cooldown)
openclaw cron run <job-id> --force

# 启用/禁用
openclaw cron enable <job-id>
openclaw cron disable <job-id>

# 删除
openclaw cron rm <job-id>

# 查看运行记录
openclaw cron runs --id <job-id> --limit 10

13.11.2 Hooks 管理

# 列出钩子
openclaw hooks list

# 查看钩子详情
openclaw hooks info <hook-id>

# 检查钩子状态
openclaw hooks check

# 启用/禁用
openclaw hooks enable <hook-id>
openclaw hooks disable <hook-id>

13.11.3 Webhook

# Gmail Pub/Sub 设置
openclaw webhooks gmail setup --account user@gmail.com

# 运行 Webhook 接收器
openclaw webhooks gmail run

13.11.4 系统事件

# 立即触发系统事件
openclaw system event --text "服务器重启完成"

# 在下一个心跳周期触发
openclaw system event --text "检查邮件" --mode next-heartbeat

# 心跳控制
openclaw system heartbeat last    # 最后一次心跳
openclaw system heartbeat enable  # 启用心跳
openclaw system heartbeat disable # 禁用心跳

# 查看系统存在状态
openclaw system presence

13.12 Node 管理

13.12.1 查看 Node 状态

# 列出所有 Node
openclaw nodes status

# 只看已连接的
openclaw nodes status --connected

# 查看 Node 详情
openclaw nodes describe --node "iPhone"

13.12.2 Node 命令调用

# 通用调用
openclaw nodes invoke --node "iPhone" \
  --command canvas.navigate \
  --params '{"url":"http://gateway:18789/__openclaw__/canvas/"}'

# 拍照
openclaw nodes camera snap --node "iPhone" --facing back

# 录制视频
openclaw nodes camera clip --node "iPhone" --duration 10s

# Canvas 快照
openclaw nodes canvas snapshot --node "iPhone" --format jpeg

# 屏幕录制
openclaw nodes screen record --node "MacBook" --duration 10s

# 获取位置
openclaw nodes location get --node "iPhone"

# 远程执行命令
openclaw nodes run --node "MacBook" --command "ls -la ~/Desktop"

# 发送通知
openclaw nodes notify --node "MacBook" \
  --title "提醒" --body "该开会了" --priority timeSensitive

13.12.3 无头 Node 服务

# 安装无头 Node 服务
openclaw node install --host gateway-host --port 18789

# 启动/停止/重启
openclaw node start
openclaw node stop
openclaw node restart

# 前台运行(调试用)
openclaw node run --host gateway-host --port 18789

# 查看状态
openclaw node status

13.12.4 设备配对

# 查看待配对设备
openclaw devices list

# 批准配对
openclaw devices approve <requestId>
openclaw devices approve --latest  # 批准最新的请求

# 拒绝配对
openclaw devices reject <requestId>

# 移除已配对设备
openclaw devices remove <deviceId>

# 清除所有待配对请求
openclaw devices clear --yes --pending

13.13 浏览器控制

OpenClaw 的浏览器控制 CLI 让你可以通过命令行操控 Chrome/Brave/Edge:

# 管理浏览器
openclaw browser status
openclaw browser start
openclaw browser stop
openclaw browser tabs

# 打开和导航
openclaw browser open https://example.com
openclaw browser navigate https://example.com --target-id <tab-id>

# 截图和快照
openclaw browser screenshot --type png
openclaw browser snapshot --format aria

# 交互操作
openclaw browser click <ref>
openclaw browser type <ref> "Hello, World!" --submit
openclaw browser press Enter
openclaw browser select <ref> "Option 1" "Option 2"

# 执行 JavaScript
openclaw browser evaluate --fn "() => document.title"

# 管理配置文件
openclaw browser profiles
openclaw browser create-profile --name work --color "#FF0000"

13.14 记忆、技能和插件

13.14.1 记忆管理

# 查看记忆索引状态
openclaw memory status

# 重建索引
openclaw memory index

# 语义搜索
openclaw memory search "如何配置 Telegram 通道"
openclaw memory search --query "安全最佳实践"

13.14.2 技能管理

# 列出技能
openclaw skills list
openclaw skills list --eligible  # 只显示就绪的技能
openclaw skills list -v          # 包含缺失依赖详情

# 查看技能详情
openclaw skills info <skill-name>

# 检查技能就绪状态
openclaw skills check

# 从 ClawHub 安装
openclaw skills search "web search"
openclaw skills install <slug>

# 更新技能
openclaw skills update <slug>
openclaw skills update --all

13.14.3 插件管理

# 列出插件
openclaw plugins list

# 查看插件详情
openclaw plugins inspect <id>

# 安装插件
openclaw plugins install <path-or-npm-spec>

# 启用/禁用
openclaw plugins enable <id>
openclaw plugins disable <id>

# 更新插件
openclaw plugins update <id>

# 诊断插件加载错误
openclaw plugins doctor

# 浏览插件市场
openclaw plugins marketplace list <marketplace-name>

13.15 安全和凭证管理

13.15.1 安全审计

# 基础审计
openclaw security audit

# 深度审计(含实时 Gateway 探针)
openclaw security audit --deep

# 自动修复
openclaw security audit --fix

# 机器可读
openclaw security audit --json

13.15.2 凭证管理

# 重新解析 SecretRef 并原子交换运行时快照
openclaw secrets reload

# 扫描明文残留、未解析引用和优先级漂移
openclaw secrets audit
openclaw secrets audit --allow-exec  # 允许执行 exec provider

# 交互式配置凭证 Provider
openclaw secrets configure

# 应用凭证计划文件
openclaw secrets apply --from plan.json
openclaw secrets apply --from plan.json --dry-run

13.15.3 命令审批

# 查看当前审批策略
openclaw approvals get

# 设置审批策略
openclaw approvals set --security allowlist --ask on-miss

# 管理白名单
openclaw approvals allowlist add "/usr/bin/git"
openclaw approvals allowlist remove "/usr/bin/git"

13.15.4 沙盒管理

# 列出沙盒
openclaw sandbox list

# 重建沙盒
openclaw sandbox recreate

# 解释当前沙盒配置
openclaw sandbox explain

13.16 调试工具

13.16.1 状态诊断

# 快速状态
openclaw status

# 完整诊断(可粘贴分享)
openclaw status --all

# 深度诊断(探测通道)
openclaw status --deep

# 包含模型用量
openclaw status --usage

# Gateway 健康检查
openclaw health
openclaw health --json --timeout 5000

13.16.2 实时日志

# 跟随日志
openclaw logs --follow

# 限制行数
openclaw logs --limit 200

# 纯文本
openclaw logs --plain

# JSON 格式(每行一个 JSON 对象)
openclaw logs --json

13.16.3 终端 UI

# 打开终端 UI
openclaw tui

# 指定连接参数
openclaw tui --url ws://gateway:18789 --token $TOKEN

# 带初始消息
openclaw tui --message "你好"

13.17 工作流自动化实战

CLI 的真正威力在于组合——把多个命令串联成自动化工作流。

13.17.1 场景一:部署后自动验证

#!/bin/bash
# deploy-verify.sh — 部署后自动验证脚本

set -euo pipefail

echo "=== 1. Gateway 健康检查 ==="
openclaw gateway status --require-rpc --json | jq '.'

echo "=== 2. 通道状态 ==="
openclaw channels status --probe

echo "=== 3. 模型凭证 ==="
openclaw models status --check

echo "=== 4. 安全审计 ==="
openclaw security audit --json | jq '.passed'

echo "=== 5. 配置验证 ==="
openclaw config validate

echo "✅ 所有检查通过"

13.17.2 场景二:批量添加多个通道

#!/bin/bash
# batch-channels.sh — 批量配置通道

# Telegram
openclaw channels add --channel telegram \
  --account main --name "Main Bot" \
  --token "$TELEGRAM_BOT_TOKEN"

# Discord
openclaw channels add --channel discord \
  --account main --name "Main Bot" \
  --token "$DISCORD_BOT_TOKEN"

# Slack
openclaw channels add --channel slack \
  --account main --name "Main Bot" \
  --token "$SLACK_BOT_TOKEN"

# 绑定到 Agent
openclaw agents bind --agent main \
  --bind telegram:main \
  --bind discord:main \
  --bind slack:main

# 重启 Gateway
openclaw gateway restart

# 验证
sleep 5
openclaw channels status --probe

13.17.3 场景三:模型故障切换

#!/bin/bash
# model-failover.sh — 模型故障自动切换

PRIMARY="anthropic/claude-opus-4-6"
FALLBACKS=("openai/gpt-4o" "google/gemini-2.5-pro")

# 检查主模型
if openclaw models status --probe --probe-provider anthropic 2>/dev/null; then
  echo "主模型 $PRIMARY 正常"
  exit 0
fi

echo "主模型不可用,尝试备选..."

for model in "${FALLBACKS[@]}"; do
  provider=$(echo "$model" | cut -d/ -f1)
  if openclaw models status --probe --probe-provider "$provider" 2>/dev/null; then
    echo "切换到备选模型: $model"
    openclaw models set "$model"
    exit 0
  fi
done

echo "❌ 所有模型都不可用"
exit 1

13.17.4 场景四:CI/CD 集成

#!/bin/bash
# ci-check.sh — CI/CD 中的 OpenClaw 检查

set -euo pipefail

# 非交互式环境
export OPENCLAW_NO_RESPAWN=1

echo "--- Config Validate ---"
openclaw config validate --json | jq '.'

echo "--- Security Audit ---"
RESULT=$(openclaw security audit --json)
echo "$RESULT" | jq '.'
if echo "$RESULT" | jq -e '.passed == false'; then
  echo "安全审计未通过"
  exit 1
fi

echo "--- Models Check ---"
openclaw models status --check
# 退出码:0=正常, 1=过期, 2=即将过期

echo "--- Skills Check ---"
openclaw skills check

echo "--- Gateway Dry Run ---"
openclaw gateway run --allow-unconfigured --timeout 5000 2>&1 | head -20 || true

echo "✅ CI 检查完成"

13.17.5 场景五:每日健康报告

#!/bin/bash
# daily-report.sh — 每日健康报告(配合 Cron 使用)

REPORT="/tmp/openclaw-health-$(date +%Y%m%d).txt"

{
  echo "=== OpenClaw 每日健康报告 ==="
  echo "日期: $(date)"
  echo ""

  echo "--- Gateway 状态 ---"
  openclaw gateway status --json 2>/dev/null | jq '.' || echo "Gateway 不可达"
  echo ""

  echo "--- 通道状态 ---"
  openclaw channels status 2>/dev/null || echo "通道检查失败"
  echo ""

  echo "--- 模型状态 ---"
  openclaw models status --check 2>/dev/null && echo "模型正常" || echo "模型异常"
  echo ""

  echo "--- 安全审计 ---"
  openclaw security audit 2>/dev/null || echo "安全审计失败"
  echo ""

  echo "--- 活跃会话 ---"
  openclaw sessions --active 1440 2>/dev/null || echo "无活跃会话"
  echo ""

  echo "--- 磁盘使用 ---"
  du -sh ~/.openclaw/ 2>/dev/null || echo "状态目录不可访问"

} > "$REPORT"

# 通过 Agent 发送报告
openclaw agent --message "请阅读并总结这个健康报告:$(cat $REPORT)" --deliver

⚠️ 踩坑记录

问题:脚本中 openclaw models status --check 返回退出码 2,但脚本继续执行了。

原因set -e|| 右侧的命令不会生效。

解决:在需要严格检查退出码的地方,直接使用 if 语句或单独的检查命令。

13.18 --json 的一致性模式

几乎所有 CLI 命令都支持 --json 标志。在自动化工作流中,这是你最重要的工具——它提供稳定的、机器可解析的输出格式。

# 用 jq 提取特定字段
openclaw channels list --json | jq '.channels[] | select(.connected == true)'

# 用 grep 过滤
openclaw models status --json | grep -o '"provider":"[^"]*"'

# 存入文件供后续分析
openclaw security audit --json > /var/log/openclaw/audit-$(date +%Y%m%d).json

注意:当使用 --url 覆盖 Gateway 地址时,必须同时显式传递 --token--password——CLI 不会自动使用配置文件中的凭证。

本章小结

  • CLI 是 OpenClaw 的完整自动化接口,能做一切 GUI 能做的事
  • --dev--profile 提供多环境隔离
  • gateway status / gateway probe 是 Gateway 诊断的核心命令
  • config set 支持四种模式:值、SecretRef 构建、Provider 构建、批量
  • --dry-run 让你预览配置变更而不写入
  • models status --probe 实时探测模型可用性
  • agent --message + --deliver 实现脚本化的 Agent 对话
  • --json 输出模式是构建自动化工作流的基础
  • 组合多个 CLI 命令可以构建部署验证、故障切换、CI/CD、每日报告等自动化流程

下一步

CLI 让你能"操控"OpenClaw 的一切,但操控不等于"优化"。下一章深入性能优化与调试——从 Token 使用优化到 Prompt Caching,从压缩策略到常见问题排查,让你的 Agent 又快又省。