#!/bin/bash # 用 Zero Trust 的 Tunnel Token 建具名隧道。 # # 为什么用这个而不是 cloudflared tunnel login: # 实测这条网络下 login 流程取证书失败(Failed to fetch resource), # 而 Token 方案**不需要证书文件**,纯复制粘贴, # 公网入口在 Cloudflare 面板上配一次就行。 # # 用法: # bash setup_tunnel_token.sh set -u TOKEN="${1:-}" DOMAIN="${2:-xxmxxs.top}" HOSTNAME_FULL="${3:-relay.${DOMAIN}}" RELAY_DIR=/root/lanremote-relay CF_DIR=/root/.cloudflared echo "============================================================" echo " 用 Token 建具名隧道" echo "============================================================" echo if [ -z "$TOKEN" ]; then echo " ✗ 没给 token" echo " 用法: bash $0 " exit 1 fi case "$TOKEN" in eyJ*) ;; *) echo " ⚠ token 一般以 eyJ 开头,你给的是 ${TOKEN:0:12}…,继续试试" ;; esac echo " token 长度: ${#TOKEN}" echo " 域名: $HOSTNAME_FULL" echo # ---------- 0. 先验证 token 能不能连上 ---------- echo "[0/4] 验证 token" mkdir -p "$CF_DIR" TMP_LOG=/tmp/tunnel_token_probe.log : > "$TMP_LOG" timeout 45 cloudflared tunnel --no-autoupdate --edge-ip-version 4 \ run --token "$TOKEN" > "$TMP_LOG" 2>&1 & PROBE=$! sleep 30 if grep -q 'Registered tunnel connection' "$TMP_LOG"; then echo " ✓ token 有效,隧道已连上 Cloudflare" OK=1 else echo " ⚠ 30 秒内没看到连接成功,日志:" tail -6 "$TMP_LOG" | sed 's/^/ /' OK=0 fi kill "$PROBE" 2>/dev/null || true wait "$PROBE" 2>/dev/null || true if [ "$OK" != "1" ]; then echo echo " token 可能不对,或者这条线路到 Cloudflare 的连接有问题。" echo " 还是继续装一遍服务 —— 有时候第一次慢,之后就好了。" fi # ---------- 1. 写 systemd 服务 ---------- echo echo "[1/4] 写 systemd 服务" cat > /etc/systemd/system/lanremote-tunnel.service < "$RELAY_DIR/public_url.txt" cat "$RELAY_DIR/public_url.txt" | sed 's/^/ /' # ---------- 3. 重启 ---------- echo echo "[3/4] 重启服务" systemctl stop lanremote-tunnel 2>/dev/null || true pkill -f 'cloudflared tunnel' 2>/dev/null || true sleep 2 rm -f "$RELAY_DIR/tunnel.log" systemctl daemon-reload systemctl enable lanremote-tunnel >/dev/null 2>&1 systemctl start lanremote-tunnel sleep 15 echo " 服务状态: $(systemctl is-active lanremote-tunnel)" echo " 日志尾部:" tail -5 "$RELAY_DIR/tunnel.log" 2>/dev/null | sed 's/^/ /' # ---------- 4. 验证 ---------- echo echo "[4/4] 验证 https://$HOSTNAME_FULL" for i in 1 2 3 4 5 6 7 8; do C=$(timeout 15 curl -4 -s -o /dev/null -w '%{http_code}' \ "https://$HOSTNAME_FULL/v1/health" 2>/dev/null) printf " 第 %d 次: HTTP %s\n" "$i" "${C:-超时}" if [ "$C" = "200" ]; then echo echo "============================================================" echo " ✓ 成功了!固定地址:" echo " https://$HOSTNAME_FULL" echo echo " 接下来在被控端执行一次:" echo " LanRemote-Agent.exe --relay https://$HOSTNAME_FULL" echo " 手表首页「中转设置」填同一个地址。" echo "============================================================" exit 0 fi sleep 10 done echo echo " ✗ 还没通。可能原因:" echo " 1. Cloudflare 面板上还没加 Public Hostname" echo " (Subdomain=relay Domain=$DOMAIN Service=HTTP://localhost:8080)" echo " 2. DNS 还没生效,等几分钟" echo " 3. 隧道没连上,看日志:" echo " journalctl -u lanremote-tunnel -n 20" exit 1