Files
wechatAiclaw/scripts/expose-proxy-with-cloudflared.sh
丹尼尔 bdba4ec071 fix
2026-03-12 11:52:04 +08:00

66 lines
2.1 KiB
Bash
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# 用 cloudflared 暴露本机 8899代理桥接将公网 URL 写入 .env 的 HTTP_PROXY/HTTPS_PROXY
# 前提先在本机跑起代理桥接python scripts/local_proxy_bridge.py且 8899 可访问
set -e
cd "$(dirname "$0")/.."
if ! command -v cloudflared >/dev/null 2>&1; then
echo "未检测到 cloudflared。请先安装"
echo " brew install cloudflared # macOS"
echo " 或 https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/download-and-install/install-cloudflared/"
exit 1
fi
LOG="/tmp/cloudflared-8899.log"
rm -f "$LOG"
echo "启动 cloudflared 隧道 -> http://127.0.0.1:8899 ..."
cloudflared tunnel --url http://127.0.0.1:8899 > "$LOG" 2>&1 &
CF_PID=$!
echo $CF_PID > /tmp/cloudflared-8899.pid
echo "等待隧道 URL约 515 秒)..."
PUBLIC_URL=""
for i in $(seq 1 20); do
sleep 1
if [ -f "$LOG" ] && [ -s "$LOG" ]; then
PUBLIC_URL=$(grep -oE 'https://[a-zA-Z0-9][-a-zA-Z0-9.]*\.trycloudflare\.com' "$LOG" 2>/dev/null | head -1)
[ -z "$PUBLIC_URL" ] && PUBLIC_URL=$(grep -oE 'https://[^[:space:]]+trycloudflare\.com' "$LOG" 2>/dev/null | head -1)
if [ -n "$PUBLIC_URL" ]; then
break
fi
fi
done
if [ -z "$PUBLIC_URL" ]; then
echo "未从 cloudflared 输出解析到 URL。请查看: cat $LOG"
kill $CF_PID 2>/dev/null || true
rm -f /tmp/cloudflared-8899.pid
exit 1
fi
echo "隧道地址: $PUBLIC_URL"
# 写入 .env
ENV_FILE=".env"
touch "$ENV_FILE"
_upsert() {
local key="$1" val="$2"
if grep -q "^${key}=" "$ENV_FILE" 2>/dev/null; then
if [[ "$(uname)" == "Darwin" ]]; then
sed -i '' "s|^${key}=.*|${key}=${val}|" "$ENV_FILE"
else
sed -i "s|^${key}=.*|${key}=${val}|" "$ENV_FILE"
fi
else
echo "${key}=${val}" >> "$ENV_FILE"
fi
}
_upsert "HTTP_PROXY" "$PUBLIC_URL"
_upsert "HTTPS_PROXY" "$PUBLIC_URL"
echo "已写入 $ENV_FILE: HTTP_PROXY / HTTPS_PROXY = $PUBLIC_URL"
echo ""
echo "cloudflared 已在后台运行 (PID $CF_PID)。停止: kill $CF_PID 或 kill \$(cat /tmp/cloudflared-8899.pid)"
echo "请重启本项目的后端使代理生效7006 将经此地址使用你的本机代理(8899->7890)。"