SSH 除了可以访问服务器,还可以创建加密隧道,充当两台服务器之间的通信加密跳板,使得原本不加密的通信变成加密通信。这个功能称为端口转发(port forwarding),又称 SSH 隧道(tunnel)。
这里介绍本地转发和远程转发两种场景。需要注意的是,对于openssh的不同版本实现,默认值略有差异,但命令语法相同。提示:ssh转发缺点同样是性能不足,所以在生产环境下慎用。
-L监听
Specifies that the given port on the local (client) host is to be forwarded to the given host and port on the remote side.
在本地启动local_port监听,将访问流量转发到remote_host:remote_port,默认将local_port绑定到localhost,需要指定bind_address或者*,或者增加-g参数(-Nfg)默认绑定到*上;这里tunnel_host无所谓,可以是localhost。
注意:-L的local_port绑定在执行ssh命令的机器上。
ssh -Nf -L [bind_address:]local_port:remote_host:remote_port username@跳板机IP-f 后台认证用户/密码,通常和-N连用,不用登录到远程主机。
-N 不执行脚本或命令,通常与-f连用
举例:11.41跳板机上执行如下命令,会在本机启动127.0.0.1:5022监听
ssh -L 5022:172.16.200.240:4022 xiao@localhost -fN等同 ssh -L 127.0.0.1:5022:172.16.200.240:4022 localhost -fN
举例:11.41跳板机上执行如下命令,会在本机启动192.168.11.41:5022监听,则14.229即可通过访问192.168.11.41:5022登录172.16.200.240:4022
ssh -L 192.168.11.41:5022:172.16.200.240:4022 localhost -fN
举例:11.229上执行如下命令,会在11.229上启动192.168.11.229:5022监听,收到请求后发送给192.168.11.41,192.168.11.41在讲请求转给172.16.200.240:4022
ssh -L 192.168.11.229:5022:172.16.200.240:4022 192.168.11.41 -fN
总结:-L方式监听即可在“跳板机”(当在跳板机上执行上述命令时)上也可以在其他机器(当其他机器上执行上述命令时)上,即便是在其他机器上,也不是由该机器直接转发到目标机,而是发送给“跳板机”转发给目标机。
-R转发
ssh -Nf -R [bind_address:]local_port:remote_host:remote_port username@跳板机IP
-R与-L的不同点在于local_port不绑定在执行命令的机器上,而是跳板机IP上,通过指定-g参数绑定在*上或者bind_address上,没有-g参数直接指定bind_address无效(跳板机/etc/ssh/ssh_config中,启用GatewayPorts才行)。
举例:如果14.229要用-R的方式连接172.16.200.240:4022,则需要在跳板机上执行如下命令,然后再访问192.168.11.41:5022端口,转发到172.16.200.240:4022
ssh -L 5022:172.16.200.240:4022 192.168.11.41 -fNg
总结:-R方式监听在tunnel_host上。
参考链接:
https://wangdoc.com/ssh/port-forwarding.html
https://www.jianshu.com/p/65c13339f8e2