Files
smalltown/port_forwarding.sh
Cuishibing 3f3e1c4878 init
2026-04-19 00:09:59 +08:00

74 lines
1.9 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.
#!/bin/bash
REMOTE_HOST="smalltown.dubaoda.com"
REMOTE_PORT="30000"
LOCAL_PORT="3000"
SSH_PORT="9527"
SSH_USER="cui"
SSH_PASSWORD="mima643237029"
PID_FILE="/tmp/ssh_tunnel.pid"
LOG_FILE="/tmp/ssh_tunnel.log"
start_tunnel() {
if [ -f "$PID_FILE" ]; then
OLD_PID=$(cat "$PID_FILE")
if kill -0 "$OLD_PID" 2>/dev/null; then
echo "SSH隧道已在运行 (PID: $OLD_PID)"
return
fi
rm -f "$PID_FILE"
fi
echo "正在启动SSH反向隧道..."
sshpass -p "$SSH_PASSWORD" ssh -N -g -R "0.0.0.0:$REMOTE_PORT":localhost:"$LOCAL_PORT" -p "$SSH_PORT" -o "ServerAliveInterval=60" -o "ServerAliveCountMax=3" "$SSH_USER"@"$REMOTE_HOST" > "$LOG_FILE" 2>&1 &
SSH_PID=$!
echo "$SSH_PID" > "$PID_FILE"
sleep 2
if kill -0 "$SSH_PID" 2>/dev/null; then
echo "SSH隧道已启动 (本地3000 -> 远程$REMOTE_PORT)"
else
echo "启动失败,查看日志: cat $LOG_FILE"
rm -f "$PID_FILE"
fi
}
stop_tunnel() {
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if kill -0 "$PID" 2>/dev/null; then
kill "$PID"
rm -f "$PID_FILE"
echo "SSH隧道已停止"
else
rm -f "$PID_FILE"
echo "隧道未运行"
fi
else
echo "未找到PID文件尝试直接终止"
pkill -f "ssh -N -R $REMOTE_PORT:localhost:$LOCAL_PORT"
fi
}
status_tunnel() {
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if kill -0 "$PID" 2>/dev/null; then
echo "SSH隧道正在运行 (PID: $PID)"
return
fi
fi
echo "SSH隧道未运行"
echo "尝试检测进程..."
if pgrep -f "ssh -N -R $REMOTE_PORT" > /dev/null; then
echo "发现隧道进程但无PID文件"
fi
}
case "$1" in
start) start_tunnel ;;
stop) stop_tunnel ;;
status) status_tunnel ;;
*) echo "Usage: $0 {start|stop|status}" ;;
esac