• 公网服务器A 开放端口5678(转发ssh连接),开放端口5679(监听连接状态),开放端口22
  • 内网机器B Ubuntu18.04

建立公网服务器A到内网机器B的SSH反向代理,将连接到公网服务器A 5678端口的SSH请求转发给内网机器B的22端口

修改公网服务器A的SSH配置文件/etc/ssh/sshd_config

1
GatewayPorts yes

这样可以把监听的端口绑定到任意IP 0.0.0.0上,否则只有本机127.0.0.1可以访问。
记得重启SSH服务器

1
sudo service restart sshd

用内网B机器保存公网服务器A的密钥,以便免密连接

1
ssh-copy-id [公网服务器A的用户名]@[公网服务器A的IP]

在内网B机器上尝试建立反向代理

1
ssh -NR 5678:127.0.0.1:22 公网服务器A的用户名@公网服务器A的IP

正常情况下,不用输入密码,通道即建立成功。

  • -N:只建立连接,不打开shell
  • -R:指定端口映射

AutoSSH 自动重连

使用SSH的方式不够稳定,使用AutoSSH可以自动在连接断开时自动重连,再把AutoSSH加入系统服务自动启动,则可以做到稳定的连接。

安装AutoSSH

1
sudo apt-get install -y autossh

将AutoSSH添加到开机自启

需要创建一个 /etc/systemd/system/autossh.service 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
sudo tee /etc/systemd/system/autossh.service >/dev/null <<'EOF'
[Unit]
Description=AutoSSH service for remote tunnel
After=network-online.target

[Service]
User=内网机器B的用户名
ExecStart=/usr/bin/autossh -M 5679 -N -o "StrictHostKeyChecking=false" -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 5678:localhost:22 公网服务器A的用户名@公网服务A的IP
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF

将AutoSSH交给Systemd托管,设置立即启动并下次开机自启

1
sudo systemctl daemon-reload && sudo systemctl start autossh && sudo systemctl enable autossh.service

autossh相关参数说明

  • -M: 5679 选项指定中继服务器上的监视端口,用于交换监视 SSH 会话的测试数据,需要保证该端口在服务器上未被占用。
  • -o: 用于设置 autossh 参数。
  • -f:指定 autossh 在后台运行,并不会传给 ssh。和 ssh 的 -f 不一样,autossh 指定 -f 时将无法寻求密码。指定 -f 时,会将环境变量 AUTOSSH_GATETIME 覆盖为 0!
  • -N:只建立连接,不打开shell
  • -R:指定端口映射