开发者
我要评分
获取效率
正确性
完整性
易理解
在线提单
论坛求助

配置与验证

  1. 参考下述脚本进行沙箱OpenClaw功能验证,将E2B_API_URL改为你的服务器的IP地址,端口默认3000。
    import os
    import json
    from e2b import Template, default_build_logger, wait_for_port
    from e2b import Sandbox
    # 设置E2B环境变量,IP修改为本地IP
    os.environ["E2B_API_URL"] = "http://{你的服务器IP}:3000" # API端口号默认3000
    os.environ["E2B_HTTP_SSL"] = "false"
    config_path = "/root/.e2b/config.json"
    def wait_for_openclaw(sbx, timeout=120, interval=2):
        print(f"动态监测 OpenClaw 初始化 (超时: {timeout}秒)...")
        start_time = time.time()
        while time.time() - start_time < timeout:
            elapsed = int(time.time() - start_time)
            check_process = sbx.commands.run(
                "ps aux | grep openclaw-gateway | grep -v grep || echo 'NOT_FOUND'",
                user="root"
            )
            process_running = "NOT_FOUND" not in check_process.stdout
            # 检查端口是否在侦听
            check_port = sbx.commands.run(
                "ss -tlnp | grep ':18789' || netstat -tlnp 2>/dev/null | grep ':18789' || echo 'PORT_NOT_LISTENING'",
                user="root"
            )
            port_listening = "PORT_NOT_LISTENING" not in check_port.stdout and ":18789" in check_port.stdout
            # 检查是否能响应简单的 openclaw 命令
            try:
                version_check = sbx.commands.run("openclaw --version 2>/dev/null || echo 'CMD_NOT_READY'", 
                                                  timeout=5, user="root")
                cmd_ready = "CMD_NOT_READY" not in version_check.stdout and version_check.stdout.strip()
            except:
                cmd_ready = False
            status_msg = f"[{elapsed}s] 进程: {'✓' if process_running else '✗'} | 端口: {'✓' if port_listening else '✗'} | 命令: {'✓' if cmd_ready else '✗'}"
            print(f"\r{status_msg}", end="", flush=True)
            if process_running and port_listening and cmd_ready:            
                return True
            time.sleep(interval)
        print(f"\n[✗] 等待超时 ({timeout}秒),OpenClaw 可能未正常启动")
        return False
    if __name__ == '__main__':
        print(f"读取配置文件路径:{config_path}")
        access_token = None
        team_api_key = None
        with open(config_path, "r", encoding="utf-8") as f:
            data = json.load(f)
        access_token = data.get("accessToken")
        team_api_key = data.get("teamApiKey")
        print(f"accessToken: {access_token}")
        print(f"teamApiKey: {team_api_key}")
        if not access_token or not team_api_key:
            print("警告:文件中未找到accessToken或teamApiKey字段!")
            exit(1)
        os.environ["E2B_ACCESS_TOKEN"] = access_token
        os.environ["E2B_API_KEY"] = team_api_key
        sbx = Sandbox.create("openclaw", timeout=600) # 使用刚刚build的模板创建沙箱
        print("沙箱id: ", sbx.sandbox_id)
        # 替换为你的 OpenViking URL 与 智谱 AI API KEY;若需使用其他大模型,可参照后续步骤进入沙箱完成 OpenClaw 配置
        env_str = (
            f'export OPENVIKING_BASE_URL="{os.getenv("OPENVIKING_BASE_URL", "http://127.0.0.1:1933")}"; '
            f'export ZAI_API_KEY="{os.getenv("ZAI_API_KEY", "你的APIKEY")}"; '
            f'export OPENCLAW_REAPPLY_CONFIG=1; '
        )
        # 沙箱重启OpenClaw gateway
        sbx.commands.run(
            f'{env_str} (nohup bash /usr/local/bin/entrypoint.sh > /tmp/entrypoint.log 2>&1 &) && sleep 1 && echo $!',
            timeout=10, user="root"
        )
        # 检查启动日志
        print("\n 检查启动日志...")
        log_result = sbx.commands.run("cat /tmp/entrypoint.log")
        print(log_result.stdout[-1000:] if len(log_result.stdout) > 1000 else log_result.stdout)
        if not is_ready:
            print("\n[警告] OpenClaw 可能未完全启动,继续执行后续步骤可能会失败...")
        try:
            agents_result = sbx.commands.run("openclaw agents list", timeout=60, user="root")
            print(agents_result.stdout)
        except CommandExitException as e:
            print(f"获取 agents 列表失败: {e}")
        try:
            hello_result = sbx.commands.run(
                'openclaw agent --agent main -m "将《静夜思》写到poem.txt文件中"',
                timeout=0,
                user="root"
            )
            print("Agent 响应:")
            print(hello_result.stdout)
        except CommandExitException as e:
            print(f"Agent 测试失败: {e}")
  2. 沙箱创建完成后,可通过终端SSH连接沙箱,进行OpenClaw配置。
    export SANDBOX_ID=<上一步输出的沙箱ID> && echo "127.0.0.1 8081-${SANDBOX_ID}.e2b.app" | sudo tee -a /etc/hosts > /dev/null 2>&1 && ssh -o "ProxyCommand=websocat --binary -B 65536 ws://8081-${SANDBOX_ID}.e2b.app" -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" user@8081-${SANDBOX_ID}.e2b.app
    • 如果要配置其他ModelProvider,可以SSH进入沙箱修改“~/.openclaw/openclaw.json”,参考Openclaw Model Provider配置Openclaw Config文件配置进行更多元化配置,也可以参考Openclaw onboard配置进行交互性可视化配置。
    • 8081:E2B沙箱实例暴露WebSocket代理端口(SSH流量由此转发)。
    • -B 65536:设置websocat数据缓冲区大小为64KB,提升传输效率。
  3. 若需通过本地电脑浏览器访问服务器沙箱内的OpenClaw。
    1. 按前文方法SSH登录沙箱终端,编辑“ ~/.openclaw/openclaw.json”的gateway配置,示例如下。
      "gateway": {
        "port": 18789,
        "mode": "local",
        "bind": "lan",
        "controlUi": {
          "dangerouslyAllowHostHeaderOriginFallback": true,
          "allowInsecureAuth": true,
          "dangerouslyDisableDeviceAuth": true
        },
        "auth": {
          "mode": "token",
          "token": "123456"
        },
        "remote": {
          "token": "123456"
        }
      }
      • 将gateway.bind设置为lan以支持局域网访问。
      • gateway.controlUi字段可直接复制示例内容。
      • gateway.auth.token需与gateway.remote.token取值保持一致。
    2. 在沙箱中重启gateway。
      openclaw gateway restart
    3. 在PC机中安装好websocat后,执行如下命令建立websocat链接。
      export SANDBOX_ID=你沙箱的ID; ssh -L 18789:localhost:18789 -o "ProxyCommand=websocat --binary -B 65536 ws://8081-${SANDBOX_ID}.e2b.app" -o "StrictHostKeyChecking=no" -o "UserKnownHostsFile=/dev/null" -o "ServerAliveInterval=30" -N user@8081-${SANDBOX_ID}.e2b.app
      • -L 18789:localhost:18789:将本地PC的18789端口映射到沙箱内部的18789端口(OpenClaw Gateway服务),格式为 -L <PC端口>:localhost:<沙箱内端口>。
      • 请勿使用下述Chrome不安全端口列表,否则可能导致该端口在PC浏览器中无法正常访问。

      端口

      原因

      6665~6669

      IRC与恶意软件常用端口。

      6000

      X11默认服务器端口。

      9050

      Tor默认SOCKS代理端口。

      19, 25, 110, 143, 465, 587, 993, 995...

      邮件相关端口。

    4. “C:\Windows\System32\drivers\etc\hosts”文件中追加如下内容,手动将沙箱域名绑定到私有E2B服务器的IP地址,绕过公网DNS直接访问内网服务。
      <你的服务器IP> 8081-<沙箱ID>.e2b.app
    5. 通过浏览器访问沙箱中的OpenClaw。在浏览器中输入http://127.0.0.1:18789/?token=123456即可访问,如下所示。

      输入Token后即可登录并进行交互操作。