Linux ssh 端口转发

SSH有三种端口转发模式:

  1. 本地端口转发(Local Port Forwarding)
  2. 远程端口转发(Local Port Forwarding)
  3. 动态端口转发(Dynamic Port Forwarding)

本地端口转发

使用-L参数,将发送到本地端口的请求,转发到目标端口

1
2
3
4
# -L 本地地址:本地端口:目标地址:目标端口
ssh -L <local host>:<local port>:<remote host>:<remote port> <remote user>@<remote host>
# 本地地址可忽略
ssh -L <local port>:<remote host>:<remote port> <remote user>@<remote host>

远程端口转发

ssh安全设置默认不开启远程端口转发,需要修改配置开启,GatewayPorts设置为yes

1
2
cat /etc/ssh/sshd_config|grep 'GatewayPorts'
GatewayPorts yes

使用-R参数,将发送到远程端口的请求,转发到目标端口

1
2
3
4
# -R 远程地址:远程端口:目标地址:目标端口
ssh -R <remote host>:<remote port>:<local host>:<local port> <remote user>@<remote host>
# 远程地址可忽略
ssh -R <remote port>:<local host>:<local port> <remote user>@<remote host>

动态端口转发

使用-D参数,绑定一个本地端口,目标端口不固定,在发起请求时决定

1
2
# -D 本地地址:本地端口
ssh -D <local host>:<local port> <remote user>@<remote host>

端口转发维持使用参数

-o ServerAliveInterval=60

其它参数

-f     # 后台启用
-N     # 不登录远程shell

参考