#!/bin/bash # 远程执行命令 # 用法: bash exec.sh "<命令>" [超时毫秒] set -e CONFIG_FILE="$HOME/.openclaw/cloud-deploy.json" SCRIPT_DIR="$(dirname "$0")" COMMAND="$1" TIMEOUT="${2:-120000}" if [ -z "$COMMAND" ]; then echo "用法: bash exec.sh \"<命令>\" [超时毫秒]" exit 1 fi if [ ! -f "$CONFIG_FILE" ]; then echo "📝 首次使用,自动初始化配置..." bash "$SCRIPT_DIR/init-config.sh" fi # 确保已注册 TOKEN=$(python3 -c "import json; t=json.load(open('$CONFIG_FILE')).get('token'); print(t if t else '')" 2>/dev/null) if [ -z "$TOKEN" ]; then echo "🔑 首次使用,正在注册..." bash "$SCRIPT_DIR/register.sh" TOKEN=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE'))['token'])" 2>/dev/null) fi API_URL=$(python3 -c "import json; print(json.load(open('$CONFIG_FILE'))['apiUrl'])") echo "🔧 执行远程命令..." echo " > $COMMAND" # 用 python3 安全转义命令字符串 CMD_JSON=$(python3 -c "import json; print(json.dumps('$COMMAND'))") RESPONSE=$(curl -s --max-time 300 \ -X POST "$API_URL/exec" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"command\": $CMD_JSON, \"timeout\": $TIMEOUT }" 2>/dev/null) if [ -z "$RESPONSE" ]; then echo "❌ API 无响应" exit 1 fi # 检查是否被拦截 BLOCKED=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('error', ''))" 2>/dev/null) if [ "$BLOCKED" = "blocked" ]; then RULE=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('rule', ''))" 2>/dev/null) echo "🚫 命令被安全策略拦截" echo " 规则: $RULE" exit 1 fi EXIT_CODE=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('exitCode', -1))" 2>/dev/null) STDOUT=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('stdout', ''))" 2>/dev/null) STDERR=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('stderr', ''))" 2>/dev/null) DURATION=$(echo "$RESPONSE" | python3 -c "import json,sys; d=json.load(sys.stdin); print(d.get('durationMs', 0))" 2>/dev/null) echo "" if [ "$EXIT_CODE" = "0" ]; then echo "✅ 执行成功(耗时 ${DURATION}ms)" else echo "⚠️ 执行完成,退出码: $EXIT_CODE(耗时 ${DURATION}ms)" fi if [ -n "$STDOUT" ]; then echo "--- stdout ---" echo "$STDOUT" fi if [ -n "$STDERR" ]; then echo "--- stderr ---" echo "$STDERR" fi