#!/bin/bash
# 文件名: check_and_enable_ssh_remote_forward.sh
# 说明: 检查 8201 是否对外监听, 如果不是, 修改 sshd_config 启用 GatewayPorts, 并重启 sshd

set -e

SSH_PORT=8201

echo "====== 1. 检查是否已有 8201 监听 ======"
ss -tuln | grep ":${SSH_PORT} " || {
    echo "注意: 目前没有发现端口 ${SSH_PORT} 被监听 (LISTEN)"
}

echo
echo "====== 2. 检查 sshd_config 中 GatewayPorts 配置 ======"
GW=$(grep -E "^\\s*GatewayPorts" /etc/ssh/sshd_config || true)
if [[ -z "$GW" ]]; then
    echo "sshd_config 中未设置 GatewayPorts — 建议添加 'GatewayPorts yes'"
else
    echo "sshd_config 中 GatewayPorts 设置为: $GW"
fi

echo
echo "====== 3. 如果需要 — 修改 sshd_config 启用 GatewayPorts 并重启 sshd ====="
read -p "是否自动修改为 GatewayPorts yes 并重启 ssh? (y/n) " yn
if [[ "$yn" =~ ^[Yy]$ ]]; then
    # 备份
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak_$(date +%s)
    # 如果有 GatewayPorts 行, 修改; 否则添加
    if grep -qE "^\\s*GatewayPorts" /etc/ssh/sshd_config; then
        sed -i 's/^\s*GatewayPorts.*/GatewayPorts yes/' /etc/ssh/sshd_config
    else
        echo "" >> /etc/ssh/sshd_config
        echo "GatewayPorts yes" >> /etc/ssh/sshd_config
    fi
    # 确保 AllowTcpForwarding yes (默认一般允许)
    if grep -qE "^\\s*AllowTcpForwarding" /etc/ssh/sshd_config; then
        sed -i 's/^\s*AllowTcpForwarding.*/AllowTcpForwarding yes/' /etc/ssh/sshd_config
    else
        echo "AllowTcpForwarding yes" >> /etc/ssh/sshd_config
    fi
    # 重启 sshd
    systemctl restart sshd
    echo "已重启 sshd，请等待 1-2 秒后继续执行监听检查"
    sleep 2
fi

echo
echo "====== 4. 再次检查 8201 监听, 及监听地址 ======"
ss -tuln | grep ":${SSH_PORT} " && \
    echo "发现 LISTEN —— 监听成功 " || \
    echo "仍未监听 — 请检查 sshd / 防火墙 / 日志"

echo "（如果监听, 注意: 如果看到 127.0.0.1:${SSH_PORT} — 意味着仅本地可访问; 如果看到 0.0.0.0:${SSH_PORT} 或公网 IP:${SSH_PORT} — 表示对外公开）"
