动态转发

因为 SSH 服务器要去访问哪一个网站,完全是动态的,取决于原始通信,动态转发只需要把本地端口绑定到 SSH 服务器,所以叫动态转发。

$ ssh -D port tunnel-host -N

本地转发(正向代理)

cpf

$ ssh -L port:host:hostport tunnel-host -N

上面就是将 tunnel-host 作为跳板机,在本地 port 端口与目标服务器(这里是 host)的 hostport 端口之间建立了一个 ssh 隧道。

$ ssh -L 8080:www:80 tunnel-host -N

远程转发(反向代理)

rpf

$ ssh -R port:host:hostport tunnel-host -N

访问 tunnel-host:port 会访问到本地的 host:hostport,可以通过这个功能将本地服务转发出去。

$ ssh -R 8080:192.168.1.100:80 root@x.x.x.x -p 0~65535 -N

如上,访问公网 x.x.x.x:8080 端口的话,可以访问到内网的 192.168.1.100:80。

实例

简易 VPN

$ ssh -L 233:192.168.10.10:22 root@192.168.10.11 -N

这里举例如果 A 禁止了 localhost 的 IP 地址,使其无法使用 ssh 访问 A,模拟网络中被防火墙隔离的情况。

但是这时 B 是一台没有被封禁的机器,就可以通过上述操作从 localhost 连接到 B 建立端口转发。之后如果访问 localhost 本机的 8080 端口,就会通过 B 来访问到 A 的 22 端口,这样就绕过了无法访问的情况。

两级跳板

two

端口转发可以有多级,比如新建两个 SSH 隧道,第一个隧道转发给第二个隧道,第二个隧道才能访问目标服务器。

首先,在本机新建第一级隧道。

$ ssh -L 7999:localhost:2999 tunnel1-host

上面命令在本地7999端口与tunnel1-host之间建立一条隧道,隧道的出口是tunnel1-host的localhost:2999,也就是tunnel1-host收到本机的请求以后,转发给自己的2999端口。

然后,在第一台跳板机(tunnel1-host)执行下面的命令,新建第二级隧道。

$ ssh -L 2999:target-host:7999 tunnel2-host -N

上面命令将第一台跳板机tunnel1-host的2999端口,通过第二台跳板机tunnel2-host,连接到目标服务器target-host的7999端口。

最终效果就是,访问本机的7999端口,就会转发到target-host的7999端口。

config

# ~/.ssh/config
Host *
Port 2222

Host remoteserver
HostName remote.example.com
User neo
Port 2112
$ ssh remoteserver
# 等同于
$ ssh -p 2112 neo@remote.example.com

参考:

附录

/etc/hosts.allow
/etc/hosts.deny