方案概述
通过反向 SSH 隧道,实现从外网笔记本远程 SSH 到公司内网主机。
笔记本 ──→ 云服务器 (cloud.example.com:12222) ←── 反向隧道 ←── 公司主机 (Zeus)
公司主机主动向外连接云服务器,建立反向通道,绕过公司防火墙/内网限制。
环境信息
| 角色 | 地址 | 用户 | 备注 |
|---|---|---|---|
| 笔记本 | macOS (MacBook Air) | XX | SSH 客户端 |
| 云服务器 | cloud.example.com (x.x.x.x) | root | 阿里云 ECS,中转站 |
| 公司主机 | 10.x.x.x (内网) | tsdl | 主机名 Zeus,SSH 端口 22 |
配置详情
1. 云服务器 (cloud.example.com)
启用 GatewayPorts
让反向隧道监听在 0.0.0.0(公网),而非仅 localhost。
bash
# /etc/ssh/sshd_config
GatewayPorts yes
修改后重启 sshd:
bash
systemctl restart sshd
阿里云安全组
入方向添加规则:
| 协议 | 端口 | 源 | 说明 |
|---|---|---|---|
| TCP | 12222 | 0.0.0.0/0 | 反向 SSH 隧道 |
2. 公司主机 (Zeus)
SSH 密钥(免密登录到云服务器)
生成密钥(如已有可跳过):
bash
ssh-keygen -t rsa -b 4096
将公钥 ~/.ssh/id_rsa.pub 的内容添加到云服务器的 ~/.ssh/authorized_keys。
反向隧道命令
bash
autossh -M 0 -N -p 22 \
-o "ServerAliveInterval=30" \
-o "ServerAliveCountMax=3" \
-o "StrictHostKeyChecking=no" \
-o "ExitOnForwardFailure=yes" \
-R 12222:localhost:22 root@cloud.example.com
参数说明:
| 参数 | 作用 |
|---|---|
-M 0 |
禁用 autossh 自身的监控端口,依赖 SSH 心跳 |
-N |
不执行远程命令,仅做端口转发 |
-p 22 |
显式指定云服务器 SSH 端口(公司主机默认端口可能是 2222) |
-R 12222:localhost:22 |
云服务器的 12222 端口 → 公司主机的 22 端口 |
ServerAliveInterval=30 |
每 30 秒发心跳包 |
ServerAliveCountMax=3 |
3 次心跳无响应则断开(触发 autossh 重连) |
ExitOnForwardFailure=yes |
端口绑定失败时退出(避免假连接) |
systemd 服务(开机自启)
文件:/etc/systemd/system/ssh-reverse-tunnel.service
ini
[Unit]
Description=Reverse SSH Tunnel to Cloud Server
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=tsdl
ExecStart=/usr/bin/autossh -M 0 -N -p 22 -o "ServerAliveInterval=30" -o "ServerAliveCountMax=3" -o "StrictHostKeyChecking=no" -o "ExitOnForwardFailure=yes" -R 12222:localhost:22 root@cloud.example.com
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
启用:
bash
sudo systemctl daemon-reload
sudo systemctl enable ssh-reverse-tunnel.service
sudo systemctl start ssh-reverse-tunnel.service
3. 笔记本
SSH 配置
文件:~/.ssh/config
Host company
HostName cloud.example.com
Port 12222
User tsdl
使用
bash
ssh company
免密直连公司主机。
连接流程
1. 笔记本发起 ssh company
2. SSH 连接 cloud.example.com:12222(阿里云安全组放行)
3. 云服务器 12222 端口是公司主机建立的反向隧道
4. 流量通过隧道到达公司主机的 SSH (localhost:22)
5. 登录为 tsdl 用户
日常维护
bash
# 查看隧道状态(在公司主机上)
sudo systemctl status ssh-reverse-tunnel
# 重启隧道
sudo systemctl restart ssh-reverse-tunnel
# 查看隧道日志
sudo journalctl -u ssh-reverse-tunnel -f
# 手动启动隧道(不用 systemd 时)
autossh -M 0 -f -N -p 22 -o "ServerAliveInterval=30" -o "ServerAliveCountMax=3" -o "ExitOnForwardFailure=yes" -R 12222:localhost:22 root@cloud.example.com
故障排查
| 现象 | 原因 | 解决 |
|---|---|---|
| 笔记本 ssh 超时 | 阿里云安全组未开放 12222 | 检查安全组入站规则 |
| 隧道断开 | 网络波动 | autossh 会自动重连(10秒间隔) |
| 隧道端口被占用 | 旧进程未退出 | pkill -f "ssh.*-R 12222" 后重启 |
| 公司主机无法连云服务器 | 公司 /etc/ssh/ssh_config 默认端口不是 22 |
tunnel 命令中显式指定 -p 22 |
| GatewayPorts 未生效 | sshd 未重启 | systemctl restart sshd |