SSH 隧道(SSH Tunneling)是 SSH 协议最强大的功能之一,通过端口转发实现安全的网络通信。本文聚焦 SSH 隧道的三种模式,每个命令都可直接使用。

本地端口转发(Local Forward)

将远程服务的端口映射到本地,适合访问内网服务。

基本语法

1
ssh -L [本地地址:]本地端口:目标主机:目标端口 跳板机用户@跳板机地址

实战案例:访问内网数据库

场景:跳板机 192.168.1.100 可访问内网数据库 10.0.0.50:3306

1
2
3
4
5
# 将远程 MySQL 映射到本地 3307
ssh -L 3307:10.0.0.50:3306 user@192.168.1.100

# 然后本地连接
mysql -h 127.0.0.1 -P 3307 -u dbuser -p

绑定特定接口

1
2
3
4
5
# 仅本机访问(默认)
ssh -L 3307:10.0.0.50:3306 user@192.168.1.100

# 允许其他机器访问(注意安全风险)
ssh -L 0.0.0.0:3307:10.0.0.50:3306 user@192.168.1.100

后台运行

1
2
3
4
5
# -f 后台运行,-N 不执行远程命令
ssh -fNL 3307:10.0.0.50:3306 user@192.168.1.100

# 查看进程
ps aux | grep "ssh -fN"

远程端口转发(Remote Forward)

将本地服务暴露到远程机器,适合内网穿透。

基本语法

1
ssh -R [远程地址:]远程端口:本地主机:本地端口 远程用户@远程地址

实战案例:内网服务穿透

场景:本地运行 Web 服务 localhost:8080,需要从公网服务器访问

1
2
3
4
# 在本地执行,将本地 8080 映射到远程 8888
ssh -R 8888:localhost:8080 user@public-server.com

# 其他人访问 public-server.com:8888 即可

允许外部访问

默认远程转发仅绑定远程服务器的 localhost。需要在远程服务器的 sshd_config 中配置:

1
2
# /etc/ssh/sshd_config
GatewayPorts yes

然后:

1
ssh -R 0.0.0.0:8888:localhost:8080 user@public-server.com

动态端口转发(SOCKS 代理)

创建本地 SOCKS 代理,所有流量通过 SSH 服务器转发。

基本语法

1
ssh -D [本地地址:]本地端口 用户@服务器

实战案例:安全浏览

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 创建 SOCKS5 代理
ssh -D 1080 user@remote-server.com

# Firefox 设置:
# 设置 → 网络设置 → 手动代理配置
# SOCKS Host: 127.0.0.1  Port: 1080
# 选择 SOCKS v5

# curl 使用代理
curl --socks5 127.0.0.1:1080 https://ifconfig.me

后台运行

1
ssh -fND 1080 user@remote-server.com

多跳 SSH 隧道

通过多层跳板机访问目标。

ProxyJump 方式(推荐)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 通过 jump1 访问 jump2,再访问目标
ssh -J user1@jump1.com,user2@jump2.com user3@target.com

# 或配置 ~/.ssh/config
Host target
    HostName target.com
    User user3
    ProxyJump user1@jump1.com,user2@jump2.com

# 然后直接
ssh target

嵌套隧道(传统方式)

1
2
3
4
5
# 第一跳:本地 2222 -> jump1:22
ssh -L 2222:jump2.com:22 user1@jump1.com -fN

# 第二跳:通过本地 2222 连接 jump2,转发目标
ssh -L 3307:db.internal:3306 -p 2222 user2@localhost -fN

保持连接稳定

客户端配置

1
2
3
4
# ~/.ssh/config
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3

服务器端配置

1
2
3
# /etc/ssh/sshd_config
ClientAliveInterval 60
ClientAliveCountMax 3

管理隧道

1
2
3
4
5
6
7
8
# 查看活跃隧道
ss -tlnp | grep ssh

# 终止特定隧道
pkill -f "ssh -fNL 3307"

# 终止所有后台 SSH 隧道
pkill -f "ssh -[f]?[f]?[NLDR]"

安全建议

  1. 限制转发权限:服务器端设置 AllowTcpForwarding noPermitOpen
  2. 使用密钥认证:禁用密码登录
  3. 监控隧道使用:记录 SSH 会话日志
  4. 设置超时:避免长时间闲置连接
  5. 最小权限原则:仅转发必要端口

参考来源