利用公网服务器 SSH 连接本地 Linux 服务器

前言

在没有公网 IP 的情况下,想要从外网 SSH 连接到内网机器,可以通过在公网服务器和本地机器之间建立反向 SSH 隧道来实现。本文记录完整的配置过程。

环境说明

  • 公网服务器user@your-public-server.com
  • 本地服务器:Ubuntu Desktop(需要从公网 SSH 进来)
  • 隧道端口:公网服务器的 2222 端口映射到本地的 22 端口

一、公网服务器配置

首先在公网服务器上配置 SSH,允许端口转发。

# SSH 到公网服务器
ssh user@your-public-server.com

# 编辑 SSH 配置
echo "GatewayPorts yes" >> /etc/ssh/sshd_config
echo "ClientAliveInterval 60" >> /etc/ssh/sshd_config
echo "ClientAliveCountMax 3" >> /etc/ssh/sshd_config

# 重启 SSH 服务
systemctl restart sshd

参数说明

参数 含义
GatewayPorts yes 允许外网连接转发端口
ClientAliveInterval 60 每 60 秒发送保活信号
ClientAliveCountMax 3 3 次无响应则断开

二、本地服务器配置

1. 安装并启动 SSH 服务

sudo apt update
sudo apt install -y openssh-server
sudo systemctl enable ssh
sudo systemctl start ssh

2. 配置 SSH 密钥登录

为了避免每次连接都输入密码,建议配置公钥认证。

# 本地生成密钥
ssh-keygen -t rsa

# 将公钥复制到公网服务器
ssh-copy-id user@your-public-server.com

或者手动复制公钥到公网服务器的 ~/.ssh/authorized_keys

3. 测试密钥登录

ssh user@your-public-server.com

无需密码即可登录说明配置成功。


三、建立反向隧道

使用 autossh 工具建立持久反向隧道,它会在连接断开时自动重连。

1. 安装 autossh

sudo apt install autossh

2. 手动测试隧道

autossh -M 0 -N -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 2222:localhost:22 user@your-public-server.com

参数说明

参数 含义
-M 0 不额外监听端口,改用 ServerAlive 检测
-N 只建立隧道,不执行远程命令
-R 2222:localhost:22 将公网服务器的 2222 端口转发到本地 22 端口

3. 配置开机自启

创建 systemd 服务实现开机自动启动:

sudo nano /etc/systemd/system/ssh-tunnel.service
[Unit]
Description=SSH Reverse Tunnel
After=network.target

[Service]
Type=simple
User=your-user
ExecStart=/usr/bin/autossh -M 0 -N -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 2222:localhost:22 user@your-public-server.com
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target

启用并启动服务:

sudo systemctl enable ssh-tunnel
sudo systemctl start ssh-tunnel

四、使用方法

从任何能访问公网的地方,SSH 连接到本地服务器:

ssh -p 2222 your-user@your-public-server.com

五、常用管理命令

# 查看隧道状态
sudo systemctl status ssh-tunnel

# 重启隧道
sudo systemctl restart ssh-tunnel

# 停止隧道
sudo systemctl stop ssh-tunnel

# 查看日志
journalctl -u ssh-tunnel -f

总结

通过反向 SSH 隧道和 autossh,我们实现了从公网访问内网服务器的需求。这种方式配置简单、稳定可靠,适合需要远程管理内网机器的场景。