本地转发
本地转发(local forwarding)指的是,SSH 服务器作为中介的跳板机,建立本地计算机与特定目标网站之间的加密连接。本地转发是在本地计算机的 SSH 客户端建立的转发规则。
它会指定一个本地端口(local-port),所有发向那个端口的请求,都会转发到 SSH 跳板机(tunnel-host),然后 SSH 跳板机作为中介,将收到的请求发到目标服务器(target-host)的目标端口(target-port)。
$ ssh -L local-port:target-host:target-port tunnel-host
上面命令中,-L
参数表示本地转发,local-port
是本地端口,target-host
是你想要访问的目标服务器,target-port
是目标服务器的端口,tunnel-host
是 SSH 跳板机。
举例来说,现在有一台 SSH 跳板机tunnel-host
,我们想要通过这台机器,在本地2121
端口与目标网站www.example.com
的80端口之间建立 SSH 隧道,就可以写成下面这样。
$ ssh -L 2121:www.example.com:80 tunnel-host -N
然后,访问本机的2121
端口,就是访问www.example.com
的80端口。
$ curl http://localhost:2121
注意,本地端口转发采用 HTTP 协议,不用转成 SOCKS5 协议。
另一个例子是加密访问邮件获取协议 POP3。
$ ssh -L 1100:mail.example.com:110 mail.example.com
上面命令将本机的1100端口,绑定邮件服务器mail.example.com
的110端口(POP3 协议的默认端口)。端口转发建立以后,POP3 邮件客户端只需要访问本机的1100端口,请求就会通过 SSH 跳板机(这里是mail.example.com
),自动转发到mail.example.com
的110端口。
上面这种情况有一个前提条件,就是mail.example.com
必须运行 SSH 服务器。否则,就必须通过另一台 SSH 服务器中介,执行的命令要改成下面这样。
$ ssh -L 1100:mail.example.com:110 other.example.com
上面命令中,本机的1100端口还是绑定mail.example.com
的110端口,但是由于mail.example.com
没有运行 SSH 服务器,所以必须通过other.example.com
中介。本机的 POP3 请求通过1100端口,先发给other.example.com
的22端口(sshd 默认端口),再由后者转给mail.example.com
,得到数据以后再原路返回。
注意,采用上面的中介方式,只有本机到other.example.com
的这一段是加密的,other.example.com
到mail.example.com
的这一段并不加密。
这个命令最好加上-N
参数,表示不在 SSH 跳板机执行远程命令,让 SSH 只充当隧道。另外还有一个-f
参数表示 SSH 连接在后台运行。
如果经常使用本地转发,可以将设置写入 SSH 客户端的用户个人配置文件(~/.ssh/config
)。
Host test.example.com
LocalForward client-IP:client-port server-IP:server-port