场景分析
国内开发者经常面临这样的困境:家庭宽带处于ISP级NAT后,而公司内网机器又躲在网关后面。网关只允许键盘交互式登录,但目标工作机却要求公钥认证。这种双重限制下的SSH隧道搭建,需要特殊技巧。
核心解决思路
我们需要建立双向隧道:
- 正向隧道:将本地端口映射到内网机器
- 反向隧道:将内网机器端口暴露到本地
具体实施步骤
假设网关IP为gateway.example.com,内网机器为192.168.1.100
1. 准备密钥对
在家庭电脑生成密钥:
ssh-keygen -t ed25519 -f ~/.ssh/work_tunnel
2. 配置网关跳转
创建SSH配置文件(~/.ssh/config):
Host gateway
HostName gateway.example.com
User your_username
PreferredAuthentications keyboard-interactive
Host work_machine
HostName 192.168.1.100
User work_username
ProxyJump gateway
IdentityFile ~/.ssh/work_tunnel
ServerAliveInterval 60
3. 建立正向隧道
将本地2222端口映射到内网机器的22端口:
ssh -N -L 2222:192.168.1.100:22 gateway
4. 建立反向隧道
在内网机器上执行:
ssh -N -R 2222:localhost:22 -i ~/.ssh/work_tunnel user@home-machine
自动化方案
使用autossh保持隧道稳定:
autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -L 2222:192.168.1.100:22 gateway
Git仓库同步示例
配置本地git使用隧道:
git remote add work ssh://work_username@localhost:2222/~/repo.git
git push work master
安全注意事项
- 使用ed25519算法替代RSA
- 限制隧道端口的绑定地址为127.0.0.1
- 定期轮换密钥
- 在网关配置中禁用端口转发(如可能)
排错技巧
检查隧道状态的命令:
ss -tulnp | grep 2222
ssh -v work_machine