返回

OpenClaw 源码解析(五):部署与安全——生产级实践

从开发到生产的完整指南:认证机制选择、网络架构设计、密钥管理、监控告警、故障排查,让 OpenClaw 安全稳定运行。

适用版本: OpenClaw v2026.3 阅读时间: 约 35 分钟 前置知识: 阅读前四篇文章,理解系统架构 源码位置: src/config/, src/auth/, src/utils/

开篇:从开发到生产的跨越

前四篇文章,我们深入理解了 OpenClaw 的架构和扩展机制。现在,让我们面对一个更实际的问题:

如何把 OpenClaw 从开发环境安全地部署到生产环境?

开发环境下的 OpenClaw 很简单:openclaw gateway start,然后就能用了。但生产环境需要考虑:

flowchart TB
    subgraph Dev["开发环境"]
        D1["本地启动"]
        D2["无认证"]
        D3["控制台日志"]
        D4["内存存储"]
    end

    subgraph Prod["生产环境"]
        P1["安全启动"]
        P2["认证授权"]
        P3["结构化日志"]
        P4["持久化存储"]
        P5["监控告警"]
        P6["备份恢复"]
    end

    Dev --> |跨越| Prod

    style Dev fill:#e3f2fd
    style Prod fill:#fff3e0

本文回答核心问题:

生产环境中,如何确保 OpenClaw 安全、稳定、可观测地运行?

认证机制:谁能访问?

问题:如何保护 Gateway API?

Gateway 暴露 WebSocket API,如果没有认证,任何人都能调用。

三种认证方式对比

flowchart TB
    subgraph Token["Token 认证"]
        T1["简单易用"]
        T2["Bearer Token"]
        T3["适合 API 调用"]
    end

    subgraph Password["Password 认证"]
        P1["传统方式"]
        P2["用户名密码"]
        P3["适合人类用户"]
    end

    subgraph Tailscale["Tailscale 认证"]
        TS1["零信任网络"]
        TS2["设备级认证"]
        TS3["适合企业部署"]
    end

    style Token fill:#e8f5e9
    style Password fill:#fff3e0
    style Tailscale fill:#e3f2fd
方式 安全性 易用性 适用场景
Token 中等 API 集成、脚本调用
Password 开发测试、内部网络
Tailscale 中等 企业生产、远程访问

Token 认证实现

# ~/.openclaw/openclaw.yaml
auth:
  method: token
  tokens:
    - name: "api-token"
      value: "your-secret-token-here"
      permissions: ["read", "write"]

    - name: "readonly-token"
      value: "another-token"
      permissions: ["read"]
// src/auth/token.ts
export class TokenAuth implements AuthProvider {
  private tokens: Map<string, TokenInfo>;

  async validate(headers: Headers): Promise<AuthResult> {
    const authHeader = headers.get("Authorization");
    if (!authHeader?.startsWith("Bearer ")) {
      return { valid: false, error: "Missing or invalid Authorization header" };
    }

    const token = authHeader.slice(7);
    const info = this.tokens.get(token);

    if (!info) {
      return { valid: false, error: "Unknown token" };
    }

    return {
      valid: true,
      principal: { name: info.name, permissions: info.permissions },
    };
  }
}

Tailscale 集成

flowchart LR
    subgraph Internet["互联网"]
        ATT["攻击者"]
    end

    subgraph Tailscale["Tailscale 网络"]
        TS["Tailnet<br/>100.x.y.z"]
        GW["Gateway<br/>只监听 Tailscale IP"]
    end

    subgraph Channels["消息渠道"]
        WA["WhatsApp"]
        TG["Telegram"]
    end

    Internet -.-> |被防火墙阻止| ATT
    TS --> |加密隧道| GW
    GW --> WA
    GW --> TG

    style Tailscale fill:#e8f5e9
# ~/.openclaw/openclaw.yaml
server:
  # 只监听 Tailscale IP,不暴露到公网
  host: "100.x.y.z"  # 你的 Tailscale IP
  port: 18789

auth:
  method: tailscale
  # Tailscale 认证由网络层完成
  # 可选:进一步验证用户身份
  tailscale:
    requireEmail: true
    allowedEmails:
      - "[email protected]"
      - "[email protected]"

认证流程对比

sequenceDiagram
    autonumber
    participant Client as 客户端
    participant Gateway as Gateway
    participant Auth as Auth Provider

    Note over Client,Auth: Token 认证
    Client->>Gateway: WebSocket 连接 + Bearer Token
    Gateway->>Auth: validate(token)
    Auth-->>Gateway: {valid: true, principal: {...}}
    Gateway-->>Client: 连接成功

    Note over Client,Auth: Tailscale 认证
    Client->>Gateway: WebSocket 连接 (通过 Tailscale)
    Note over Gateway: 连接来自 Tailscale IP<br/>自动信任
    Gateway-->>Client: 连接成功

网络暴露:边界在哪里?

问题:Gateway 应该监听哪个地址?

不同的网络暴露模式适合不同的场景。

三种暴露模式

flowchart TB
    subgraph Loopback["Loopback 模式<br/>host: 127.0.0.1"]
        L1["只允许本机访问"]
        L2["最安全"]
        L3["适合:SSH 隧道"]
    end

    subgraph LAN["LAN 模式<br/>host: 0.0.0.0"]
        LA1["允许局域网访问"]
        LA2["需要防火墙"]
        LA3["适合:家庭网络"]
    end

    subgraph Tailnet["Tailnet 模式<br/>host: 100.x.y.z"]
        T1["允许 Tailscale 网络访问"]
        T2["零信任安全"]
        T3["适合:远程办公"]
    end

    style Loopback fill:#c8e6c9
    style LAN fill:#fff9c4
    style Tailnet fill:#bbdefb

Loopback + SSH 隧道

# 在本地启动 Gateway
openclaw gateway start --host 127.0.0.1

# 在远程服务器上创建 SSH 隧道
ssh -L 18789:127.0.0.1:18789 user@server

# 现在可以通过本地 18789 访问远程 Gateway
wscat -c "ws://127.0.0.1:18789"

安全原理: SSH 隧道加密传输,不暴露端口到公网。

LAN 模式 + 防火墙

# ~/.openclaw/openclaw.yaml
server:
  host: "0.0.0.0"
  port: 18789

# 需要配合防火墙规则
# 只允许特定 IP 访问
sudo ufw allow from 192.168.1.0/24 to any port 18789

# 查看防火墙状态
sudo ufw status

Tailscale 模式

# 获取 Tailscale IP
tailscale ip

# 输出示例: 100.101.102.103
# ~/.openclaw/openclaw.yaml
server:
  host: "100.101.102.103"  # 你的 Tailscale IP
  port: 18789
# 从另一台已加入 Tailnet 的机器访问
wscat -c "ws://100.101.102.103:18789"

优势: 无需配置防火墙,Tailscale 自动处理加密和认证。

密钥管理:敏感信息去哪儿?

问题:API Key、Token 等敏感信息如何安全存储?

OpenClaw 需要存储各种敏感信息:

  • LLM API Key
  • WhatsApp 认证凭据
  • GitHub Token
  • 数据库密码

三层存储策略

flowchart TB
    subgraph Level1["第一层:环境变量"]
        E1["最安全"]
        E2["进程隔离"]
        E3["适合:容器化部署"]
    end

    subgraph Level2["第二层:加密配置文件"]
        C1["方便管理"]
        C2["支持热更新"]
        C3["适合:传统部署"]
    end

    subgraph Level3["第三层:密钥管理服务"]
        S1["企业级"]
        S2["集中管理"]
        S3["适合:大规模部署"]
    end

    Level1 --> Level2 --> Level3

    style Level1 fill:#c8e6c9
    style Level2 fill:#fff9c4
    style Level3 fill:#ffccbc

环境变量

# ~/.bashrc 或 ~/.zshrc
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GITHUB_TOKEN="ghp_..."

# 或使用 .env 文件(不要提交到 Git)
# ~/.openclaw/openclaw.yaml
providers:
  openai:
    apiKey: "${OPENAI_API_KEY}"

  anthropic:
    apiKey: "${ANTHROPIC_API_KEY}"

加密配置文件

// OpenClaw 支持配置文件加密
// src/config/encryption.ts

import { createCipheriv, createDecipheriv, randomBytes } from "crypto";

export class ConfigEncryption {
  private algorithm = "aes-256-gcm";
  private key: Buffer;

  constructor(key: string) {
    // 从主密码派生密钥
    this.key = crypto.scryptSync(key, "salt", 32);
  }

  encrypt(plaintext: string): string {
    const iv = randomBytes(16);
    const cipher = createCipheriv(this.algorithm, this.key, iv);

    let encrypted = cipher.update(plaintext, "utf8", "hex");
    encrypted += cipher.final("hex");

    const authTag = cipher.getAuthTag();

    return `${iv.toString("hex")}:${authTag.toString("hex")}:${encrypted}`;
  }

  decrypt(ciphertext: string): string {
    const [ivHex, authTagHex, encrypted] = ciphertext.split(":");

    const iv = Buffer.from(ivHex, "hex");
    const authTag = Buffer.from(authTagHex, "hex");

    const decipher = createDecipheriv(this.algorithm, this.key, iv);
    decipher.setAuthTag(authTag);

    let decrypted = decipher.update(encrypted, "hex", "utf8");
    decrypted += decipher.final("utf8");

    return decrypted;
  }
}
# 加密敏感配置
openclaw config encrypt --field "providers.anthropic.apiKey"
# 输入值: sk-ant-...
# 输出: ENC:a1b2c3...

# 配置文件中使用加密值
# ~/.openclaw/openclaw.yaml
providers:
  anthropic:
    apiKey: "ENC:a1b2c3..."

密钥管理服务(Vault)

# ~/.openclaw/openclaw.yaml
secrets:
  backend: vault
  vault:
    address: "https://vault.company.com"
    path: "secret/data/openclaw"
    # Token 从环境变量读取
    token: "${VAULT_TOKEN}"

监控与日志:系统健康吗?

问题:如何知道 OpenClaw 运行正常?

生产环境需要可观测性:知道系统当前状态、发现问题、追溯原因。

可观测性三支柱

flowchart TB
    subgraph Observability["可观测性"]
        M["Metrics<br/>指标"]
        L["Logs<br/>日志"]
        T["Traces<br/>追踪"]
    end

    subgraph Tools["工具"]
        PROM["Prometheus"]
        LOKI["Loki"]
        JAEGER["Jaeger"]
    end

    M --> PROM
    L --> LOKI
    T --> JAEGER

    style Observability fill:#e8f5e9

结构化日志

# ~/.openclaw/openclaw.yaml
logging:
  level: info
  format: json  # 结构化格式
  output: /var/log/openclaw/gateway.log

  # 字段配置
  fields:
    include:
      - timestamp
      - level
      - message
      - traceId
      - sessionId
      - duration
// 日志示例
{
  "timestamp": "2026-03-13T10:30:45.123Z",
  "level": "info",
  "message": "Turn completed",
  "traceId": "abc-123",
  "sessionId": "whatsapp:+1234567890",
  "duration": 2345,
  "tokens": {
    "input": 150,
    "output": 250
  }
}

Prometheus 指标

// src/metrics/prometheus.ts
import { Counter, Histogram, Gauge, collectDefaultMetrics } from "prom-client";

// 启用默认指标
collectDefaultMetrics();

// 自定义指标
export const messagesReceived = new Counter({
  name: "openclaw_messages_received_total",
  help: "Total number of messages received",
  labelNames: ["channel", "isGroup"],
});

export const turnDuration = new Histogram({
  name: "openclaw_turn_duration_seconds",
  help: "Duration of agent turns",
  labelNames: ["agent", "provider"],
  buckets: [0.1, 0.5, 1, 2, 5, 10, 30, 60],
});

export const activeSessions = new Gauge({
  name: "openclaw_active_sessions",
  help: "Number of active sessions",
});

export const toolCalls = new Counter({
  name: "openclaw_tool_calls_total",
  help: "Total number of tool calls",
  labelNames: ["tool", "success"],
});
# ~/.openclaw/openclaw.yaml
metrics:
  enabled: true
  port: 9090  # Prometheus 拉取端口
# prometheus.yml
scrape_configs:
  - job_name: "openclaw"
    static_configs:
      - targets: ["localhost:9090"]

告警规则

# alerting-rules.yml
groups:
  - name: openclaw
    rules:
      - alert: HighLatency
        expr: histogram_quantile(0.99, rate(openclaw_turn_duration_seconds_bucket[5m])) > 30
        for: 5m
        labels:
          severity: warning
        annotations:
          summary: "High turn latency"
          description: "99th percentile turn latency is {{ $value }}s"

      - alert: HighErrorRate
        expr: rate(openclaw_tool_calls_total{success="false"}[5m]) / rate(openclaw_tool_calls_total[5m]) > 0.1
        for: 5m
        labels:
          severity: critical
        annotations:
          summary: "High tool error rate"

      - alert: SessionMemoryHigh
        expr: openclaw_active_sessions > 100
        for: 10m
        labels:
          severity: warning
        annotations:
          summary: "Too many active sessions"

健康检查端点

# 检查 Gateway 健康状态
curl http://localhost:18789/health

# 响应示例
{
  "status": "healthy",
  "uptime": 86400,
  "version": "2026.3.0",
  "checks": {
    "database": "ok",
    "providers": {
      "openai": "ok",
      "anthropic": "ok"
    },
    "channels": {
      "whatsapp": "connected",
      "telegram": "connected"
    }
  }
}

备份与恢复:数据安全网

问题:会话数据丢失怎么办?

OpenClaw 存储的数据包括:

  • 会话历史(transcript)
  • 配置信息
  • 认证凭据
  • 插件状态

备份策略

flowchart LR
    subgraph Backup["备份策略"]
        B1["实时备份"]
        B2["定时备份"]
        B3["手动备份"]
    end

    subgraph Storage["存储位置"]
        S1["本地磁盘"]
        S2["对象存储"]
        S3["异地备份"]
    end

    Backup --> Storage

    style Backup fill:#e8f5e9
    style Storage fill:#fff3e0

自动备份配置

# ~/.openclaw/openclaw.yaml
backup:
  enabled: true

  # 定时备份
  schedule: "0 3 * * *"  # 每天凌晨 3 点

  # 保留策略
  retention:
    daily: 7      # 保留 7 天的日备份
    weekly: 4     # 保留 4 周的周备份
    monthly: 12   # 保留 12 个月的月备份

  # 存储位置
  destination:
    type: s3
    bucket: "openclaw-backups"
    prefix: "production/"

    # 或本地路径
    # type: local
    # path: /var/backups/openclaw

备份脚本

#!/bin/bash
# backup-openclaw.sh

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/var/backups/openclaw"
DATA_DIR="$HOME/.openclaw"

# 创建备份目录
mkdir -p "$BACKUP_DIR"

# 备份数据
tar -czf "$BACKUP_DIR/openclaw_$DATE.tar.gz" \
  -C "$DATA_DIR" \
  sessions/ \
  config/ \
  --exclude="*.log" \
  --exclude="cache/"

# 上传到 S3(可选)
if command -v aws &> /dev/null; then
  aws s3 cp "$BACKUP_DIR/openclaw_$DATE.tar.gz" \
    "s3://openclaw-backups/production/"
fi

# 清理旧备份(保留最近 7 天)
find "$BACKUP_DIR" -name "openclaw_*.tar.gz" -mtime +7 -delete

echo "Backup completed: openclaw_$DATE.tar.gz"

恢复流程

# 1. 停止 Gateway
openclaw gateway stop

# 2. 恢复数据
tar -xzf openclaw_20260313_030000.tar.gz -C ~/.openclaw/

# 3. 验证数据完整性
openclaw doctor --check-sessions

# 4. 重启 Gateway
openclaw gateway start

容器化部署:现代化的选择

Docker 部署

# Dockerfile
FROM node:20-alpine

WORKDIR /app

# 安装 OpenClaw
RUN npm install -g [email protected]

# 创建配置目录
RUN mkdir -p /root/.openclaw

# 复制配置文件
COPY openclaw.yaml /root/.openclaw/

# 暴露端口
EXPOSE 18789 9090

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD wget -q --spider http://localhost:18789/health || exit 1

# 启动 Gateway
CMD ["openclaw", "gateway", "start"]
# docker-compose.yml
version: "3.8"

services:
  openclaw:
    build: .
    container_name: openclaw-gateway
    restart: unless-stopped

    ports:
      - "18789:18789"
      - "9090:9090"

    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
      - GITHUB_TOKEN=${GITHUB_TOKEN}

    volumes:
      - ./data:/root/.openclaw
      - ./logs:/var/log/openclaw

    networks:
      - openclaw-network

    logging:
      driver: json-file
      options:
        max-size: "10m"
        max-file: "3"

networks:
  openclaw-network:
    driver: bridge
# 启动服务
docker-compose up -d

# 查看日志
docker-compose logs -f

# 健康检查
docker-compose ps

Kubernetes 部署

# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: openclaw-gateway
  labels:
    app: openclaw
spec:
  replicas: 1
  selector:
    matchLabels:
      app: openclaw
  template:
    metadata:
      labels:
        app: openclaw
    spec:
      containers:
        - name: gateway
          image: openclaw/gateway:2026.3
          ports:
            - containerPort: 18789
              name: api
            - containerPort: 9090
              name: metrics

          env:
            - name: OPENAI_API_KEY
              valueFrom:
                secretKeyRef:
                  name: openclaw-secrets
                  key: openai-api-key

            - name: ANTHROPIC_API_KEY
              valueFrom:
                secretKeyRef:
                  name: openclaw-secrets
                  key: anthropic-api-key

          volumeMounts:
            - name: config
              mountPath: /root/.openclaw
            - name: data
              mountPath: /root/.openclaw/sessions

          livenessProbe:
            httpGet:
              path: /health
              port: 18789
            initialDelaySeconds: 10
            periodSeconds: 30

          readinessProbe:
            httpGet:
              path: /health
              port: 18789
            initialDelaySeconds: 5
            periodSeconds: 10

          resources:
            requests:
              memory: "256Mi"
              cpu: "250m"
            limits:
              memory: "1Gi"
              cpu: "1"

      volumes:
        - name: config
          configMap:
            name: openclaw-config
        - name: data
          persistentVolumeClaim:
            claimName: openclaw-pvc
# k8s/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: openclaw-service
spec:
  selector:
    app: openclaw
  ports:
    - port: 18789
      targetPort: 18789
      name: api
    - port: 9090
      targetPort: 9090
      name: metrics

实战演练:部署一个多渠道生产实例

场景描述

部署一个支持 WhatsApp 和 Telegram 的生产级 OpenClaw,要求:

  • 通过 Tailscale 远程访问
  • 结构化日志
  • Prometheus 监控
  • 自动备份

步骤 1:准备环境

# 安装 Tailscale
curl -fsSL https://tailscale.com/install.sh | sh
sudo tailscale up

# 获取 Tailscale IP
TAILSCALE_IP=$(tailscale ip)
echo "Tailscale IP: $TAILSCALE_IP"

# 创建目录
mkdir -p ~/.openclaw/{sessions,logs,backups}

步骤 2:配置文件

# ~/.openclaw/openclaw.yaml
# 基础配置
server:
  host: "${TAILSCALE_IP}"  # 只监听 Tailscale
  port: 18789

# 认证
auth:
  method: tailscale

# Provider 配置
providers:
  openai:
    apiKey: "${OPENAI_API_KEY}"
    defaultModel: "gpt-4"

  anthropic:
    apiKey: "${ANTHROPIC_API_KEY}"
    defaultModel: "claude-sonnet-4-6"

# 渠道配置
channels:
  whatsapp:
    enabled: true
    dmPolicy: pairing
    sessionScope: per-sender

  telegram:
    enabled: true
    dmPolicy: open
    sessionScope: per-sender

# 日志配置
logging:
  level: info
  format: json
  output: ~/.openclaw/logs/gateway.log

# 监控配置
metrics:
  enabled: true
  port: 9090

# 备份配置
backup:
  enabled: true
  schedule: "0 3 * * *"
  retention:
    daily: 7
  destination:
    type: local
    path: ~/.openclaw/backups

步骤 3:创建 systemd 服务

# /etc/systemd/system/openclaw.service
[Unit]
Description=OpenClaw Gateway
After=network.target tailscale.service
Requires=tailscale.service

[Service]
Type=simple
User=openclaw
Group=openclaw
WorkingDirectory=/home/openclaw

# 环境变量
EnvironmentFile=/home/openclaw/.openclaw/env

# 启动命令
ExecStart=/usr/local/bin/openclaw gateway start
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=10

# 日志
StandardOutput=append:/home/openclaw/.openclaw/logs/stdout.log
StandardError=append:/home/openclaw/.openclaw/logs/stderr.log

[Install]
WantedBy=multi-user.target
# 启用服务
sudo systemctl daemon-reload
sudo systemctl enable openclaw
sudo systemctl start openclaw

# 检查状态
sudo systemctl status openclaw

步骤 4:配置 Prometheus

# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: "openclaw"
    static_configs:
      - targets: ["${TAILSCALE_IP}:9090"]

步骤 5:验证部署

# 1. 检查健康状态
curl http://${TAILSCALE_IP}:18789/health

# 2. 测试 WebSocket 连接(从另一台 Tailscale 机器)
wscat -c "ws://${TAILSCALE_IP}:18789"

# 3. 检查 Prometheus 指标
curl http://${TAILSCALE_IP}:9090/metrics

# 4. 查看日志
tail -f ~/.openclaw/logs/gateway.log | jq .

常见陷阱

陷阱 1:认证配置错误

症状:

[ERROR] Unknown auth method: tokens
[ERROR] Gateway failed to start: invalid configuration

原因: 配置文件中的认证方法名称拼写错误,应该是 token 而不是 tokens

错误代码:

# ~/.openclaw/openclaw.yaml
auth:
  method: tokens  # 错误:应该是 token

正确代码:

# ~/.openclaw/openclaw.yaml
auth:
  method: token  # 正确
  tokens:
    - name: "api-token"
      value: "your-secret-token-here"

调试方法:

# 验证配置
openclaw config validate

# 输出示例
# ✗ Error at auth.method: "tokens" is not valid
#   Valid values: token, password, tailscale

# 查看配置帮助
openclaw config help auth.method

源码位置: src/auth/index.ts


陷阱 2:Provider API Key 无效

症状:

[ERROR] OpenAI API error: 401 Unauthorized
[ERROR] Turn failed: invalid_api_key

原因: API Key 未设置、已过期或格式错误。

错误代码:

# 环境变量未设置
providers:
  openai:
    apiKey: "${OPENAI_API_KEY}"  # 环境变量不存在

# 或 API Key 格式错误
providers:
  openai:
    apiKey: "invalid-key"  # 应该以 sk- 开头

正确代码:

# 设置环境变量
export OPENAI_API_KEY="sk-proj-..."

# 或在配置文件中使用加密值
# ~/.openclaw/openclaw.yaml
providers:
  openai:
    apiKey: "${OPENAI_API_KEY}"
    # 验证配置
    testOnStartup: true

调试方法:

# 测试 API Key
openclaw provider test openai

# 输出示例
# Testing OpenAI API...
# ✗ API key invalid: 401 Unauthorized
#   Response: {"error": {"message": "Incorrect API key provided"}}

# 查看环境变量
openclaw config resolve providers.openai.apiKey

# 输出示例
# providers.openai.apiKey: "sk-proj-***...***" (from env: OPENAI_API_KEY)

源码位置: src/providers/openai.ts


陷阱 3:Channel 连接失败

症状:

[WARN] WhatsApp channel failed to connect
[ERROR] Authentication required: please scan QR code

原因: Channel 未完成初始认证流程,或认证凭据已过期。

错误代码:

# 启动 Gateway 但未完成 Channel 配置
openclaw gateway start
# 忽略了 WhatsApp 的 QR 码扫描提示

正确代码:

# 方式一:交互式配置
openclaw channel setup whatsapp

# 方式二:扫码认证
openclaw channel whatsapp --qr

# 输出示例
# Scan this QR code with WhatsApp:
# ███████████████████████
# ███████████████████████
# ...
# Waiting for scan...

# 验证连接状态
openclaw channel status whatsapp
# 输出
# WhatsApp: connected
#   Phone: +1234567890
#   Name: My Assistant

调试方法:

# 查看 Channel 详细状态
openclaw channel status --verbose

# 输出示例
# WhatsApp:
#   Status: disconnected
#   Last error: Authentication expired
#   Last connected: 2026-03-01T10:00:00Z
#   Reconnect attempts: 3

# 重连 Channel
openclaw channel reconnect whatsapp

# 查看认证状态
openclaw channel auth-status whatsapp

源码位置: src/channels/whatsapp/


陷阱 4:Session 存储损坏

症状:

[ERROR] Failed to load session: database disk image is malformed
[ERROR] Session whatsapp:+1234567890 corrupted

原因: SQLite 数据库文件损坏,可能是因为异常关机或磁盘错误。

错误代码:

# 直接删除或修改数据库文件
rm ~/.openclaw/sessions/sessions.db
# 或在 Gateway 运行时复制文件
cp ~/.openclaw/sessions/sessions.db /backup/

正确代码:

# 1. 停止 Gateway
openclaw gateway stop

# 2. 检查数据库完整性
sqlite3 ~/.openclaw/sessions/sessions.db "PRAGMA integrity_check;"

# 3. 如果损坏,尝试修复
sqlite3 ~/.openclaw/sessions/sessions.db ".recover" > recovered.sql
sqlite3 ~/.openclaw/sessions/sessions_new.db < recovered.sql
mv ~/.openclaw/sessions/sessions_new.db ~/.openclaw/sessions/sessions.db

# 4. 或从备份恢复
openclaw backup restore --latest

# 5. 重启 Gateway
openclaw gateway start

调试方法:

# 查看会话存储状态
openclaw session storage status

# 输出示例
# Storage: SQLite
# Path: ~/.openclaw/sessions/sessions.db
# Size: 15.2 MB
# Integrity: ✗ Corrupted
# Sessions: 42 (3 unreadable)

# 导出可恢复的会话
openclaw session export --output sessions_backup.json

源码位置: src/sessions/store.ts


故障演练

演练 1:认证配置错误

目标: 观察认证配置错误时的行为和错误提示。

步骤:

# 1. 创建错误配置
cat > ~/.openclaw/openclaw.yaml << 'EOF'
auth:
  method: invalid_method  # 故意写错
EOF

# 2. 尝试启动
openclaw gateway start

# 3. 观察错误输出

预期结果:

[ERROR] Configuration validation failed
[ERROR]   at auth.method: "invalid_method" is not a valid auth method
[ERROR]   Valid options: token, password, tailscale

Hint: Run 'openclaw config validate' to check your configuration

修复方法:

# 验证配置
openclaw config validate

# 查看有效选项
openclaw config help auth.method

演练 2:API Key 无效

目标: 模拟 API Key 错误,观察系统如何处理。

步骤:

# 1. 设置错误的 API Key
export OPENAI_API_KEY="sk-invalid-key-12345"

# 2. 启动 Gateway
openclaw gateway start

# 3. 发送消息触发 LLM 调用
wscat -c "ws://127.0.0.1:18789" -H "Authorization: Bearer $TOKEN"
> {"kind":"request","id":"test","method":"message.send","params":{"sessionKey":"main","text":"Hello"}}

预期结果:

< {"kind":"event","event":"agent","payload":{"type":"error","message":"OpenAI API error: 401 Unauthorized - Incorrect API key provided","code":"invalid_api_key","retryable":false}}

修复方法:

# 设置正确的 API Key
export OPENAI_API_KEY="sk-proj-..."

# 重启 Gateway
openclaw gateway restart

演练 3:网络隔离测试

目标: 验证 Gateway 不暴露到公网。

步骤:

# 1. 配置只监听 loopback
cat > ~/.openclaw/openclaw.yaml << 'EOF'
server:
  host: 127.0.0.1
  port: 18789
EOF

# 2. 启动 Gateway
openclaw gateway start

# 3. 从本机访问(应该成功)
curl http://127.0.0.1:18789/health

# 4. 从其他机器访问(应该失败)
# 在另一台机器上执行
curl http://YOUR_SERVER_IP:18789/health

预期结果:

# 本机访问成功
{"status":"healthy","uptime":60,...}

# 远程访问失败(连接超时或拒绝)
curl: (7) Failed to connect to YOUR_SERVER_IP port 18789: Connection refused

验证方法:

# 检查监听地址
ss -tlnp | grep 18789

# 输出示例
# LISTEN  0  128  127.0.0.1:18789  0.0.0.0:*  users:(("node",pid=1234,fd=15))
# 注意:只监听 127.0.0.1,不监听 0.0.0.0

演练 4:备份恢复测试

目标: 验证备份和恢复流程正常工作。

步骤:

# 1. 创建测试会话
openclaw session create --key "test:backup-test"

# 2. 发送测试消息
wscat -c "ws://127.0.0.1:18789" -H "Authorization: Bearer $TOKEN"
> {"kind":"request","id":"test","method":"message.send","params":{"sessionKey":"test:backup-test","text":"Remember this: test data 12345"}}
# 3. 创建手动备份
openclaw backup create --output /tmp/test-backup.tar.gz

# 4. 模拟数据丢失
rm -rf ~/.openclaw/sessions/*

# 5. 验证数据丢失
openclaw session list
# 输出:No sessions found

# 6. 从备份恢复
openclaw backup restore /tmp/test-backup.tar.gz

# 7. 验证恢复
openclaw session list
# 输出应包含 test:backup-test

预期结果:

# 恢复成功
[INFO] Restoring from backup: /tmp/test-backup.tar.gz
[INFO] Extracted 1 sessions
[INFO] Restored session: test:backup-test
[INFO] Restore completed successfully

# 验证会话存在
openclaw session get test:backup-test
# 输出应显示会话详情和历史消息

故障排查:常见问题

问题 1:Gateway 启动失败

# 检查日志
journalctl -u openclaw -f

# 常见原因:
# 1. 端口被占用
sudo lsof -i :18789

# 2. 配置错误
openclaw config validate

# 3. 权限问题
ls -la ~/.openclaw/

问题 2:消息不响应

# 1. 检查 Channel 状态
openclaw channels status

# 2. 检查会话状态
openclaw sessions list

# 3. 启用调试日志
LOG_LEVEL=debug openclaw gateway start

问题 3:Token 过期

# 检查 Token 有效性
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:18789/health

# 生成新 Token
openclaw token generate --name "new-token"

问题 4:内存占用过高

# 检查会话数量
openclaw sessions list | wc -l

# 清理旧会话
openclaw sessions prune --older-than 7d

# 设置会话上限
# ~/.openclaw/openclaw.yaml
sessions:
  maxActive: 100
  cleanupInterval: "1h"

问题 5:Channel 断连

# WhatsApp 常见问题
# 1. 扫码重新连接
openclaw channel whatsapp --reconnect

# 2. 清除认证缓存
rm -rf ~/.openclaw/whatsapp/auth/*

# 3. 重新配对
openclaw channel whatsapp --setup

安全加固清单

flowchart TB
    subgraph Network["网络安全"]
        N1["使用 Tailscale"]
        N2["关闭不必要的端口"]
        N3["启用防火墙"]
    end

    subgraph Auth["认证授权"]
        A1["使用强 Token"]
        A2["定期轮换密钥"]
        A3["最小权限原则"]
    end

    subgraph Data["数据安全"]
        D1["加密敏感配置"]
        D2["定期备份"]
        D3["日志脱敏"]
    end

    subgraph Runtime["运行时安全"]
        R1["使用非 root 用户"]
        R2["限制资源使用"]
        R3["隔离进程"]
    end

    style Network fill:#c8e6c9
    style Auth fill:#bbdefb
    style Data fill:#fff9c4
    style Runtime fill:#ffccbc

快速检查命令

# 一键安全检查
openclaw doctor --security

# 输出示例:
# ✅ Gateway not exposed to public internet
# ✅ Strong authentication configured
# ⚠️  Some secrets stored in plain text
# ✅ Logging enabled
# ✅ Metrics endpoint protected

性能调优

连接数上限

Gateway 默认支持 1000 并发 WebSocket 连接:

# ~/.openclaw/openclaw.yaml
server:
  maxConnections: 1000
  # 连接超时
  connectionTimeout: 30000  # 30秒

调优建议:

场景 建议值 说明
个人使用 100 足够日常使用
小团队 (<20人) 500 支持多设备同时连接
企业部署 1000+ 需配合负载均衡

Turn 延迟优化

一次 Turn 的延迟主要来自:

flowchart LR
    subgraph Latency["Turn 延迟组成"]
        L1["消息预处理<br/>~10ms"]
        L2["LLM 首 Token<br/>~500-2000ms"]
        L3["工具执行<br/>~50-500ms"]
        L4["响应发送<br/>~10ms"]
    end

    L1 --> L2 --> L3 --> L4
优化点 方法 预期收益
LLM 调用 使用更近的 API 端点 -100ms
LLM 调用 使用更快的模型 (Haiku/Sonnet) -500ms
工具执行 并行调用独立工具 -50%
工具执行 缓存工具结果 -90% (命中时)
日志写入 异步日志 -10ms
数据库 使用内存数据库 -20ms

并行工具调用

# ~/.openclaw/openclaw.yaml
agents:
  defaults:
    # 启用并行工具调用
    parallelToolCalls: true
    # 最大并行数
    maxParallelTools: 5

内存占用优化

# ~/.openclaw/openclaw.yaml
sessions:
  # 最大活跃会话数
  maxActive: 100

  # 清理间隔
  cleanupInterval: "1h"

  # 会话超时
  timeout: "24h"

  # Transcript 限制
  transcript:
    maxTokens: 4000
    strategy: sliding_window

性能监控

# 查看实时性能指标
openclaw metrics

# 输出示例
# ┌─────────────────────┬──────────┐
# │ Metric              │ Value    │
# ├─────────────────────┼──────────┤
# │ Active Sessions     │ 23       │
# │ Active Connections  │ 15       │
# │ Avg Turn Latency    │ 1.2s     │
# │ Memory Usage        │ 256MB    │
# │ CPU Usage           │ 12%      │
# │ Messages/min        │ 45       │
# │ Tool Calls/min      │ 12       │
# └─────────────────────┴──────────┘

# 导出 Prometheus 指标
curl http://localhost:9090/metrics

性能基准测试

# 运行性能测试
openclaw benchmark --duration 60s --concurrency 10

# 输出示例
# Benchmark Results (60s, 10 concurrent users)
# ─────────────────────────────────────────
# Total Requests:       1250
# Successful:           1248 (99.8%)
# Failed:               2 (0.2%)
#
# Latency:
#   P50: 850ms
#   P90: 1.5s
#   P99: 3.2s
#   Max: 5.1s
#
# Throughput:           20.8 req/s
# Token Usage:
#   Input:              125,000 tokens
#   Output:             62,500 tokens

小结

生产环境部署 OpenClaw 需要考虑:

维度 关键点
认证 Token/Password/Tailscale 选择
网络 Loopback/LAN/Tailnet 暴露模式
密钥 环境变量 > 加密配置 > 密钥服务
监控 日志 + 指标 + 追踪
备份 定时 + 异地 + 验证
部署 容器化 > 传统部署

理解部署与安全的关键:安全是分层的,每一层都要有防护措施

关键源码文件

文件 职责
src/auth/token.ts Token 认证实现
src/auth/tailscale.ts Tailscale 认证
src/config/encryption.ts 配置加密
src/metrics/prometheus.ts Prometheus 指标
src/backup/manager.ts 备份管理
scripts/backup.sh 备份脚本

在下一篇文章中,我们将进入 架构复盘——全面审视 OpenClaw 的设计得失,以及我们能从中学到什么。


系列索引: OpenClaw 源码解析:目录索引

上一篇: OpenClaw 源码解析(四):扩展点 下一篇: OpenClaw 源码解析(六):架构复盘