ssh隧道使用技巧

ssh隧道使用技巧

本文来自:https://iximiuz.com/en/posts/ssh-tunnels/
所有知识总结为一张图:https://moneyslow.com/images/ssh-tunnels.png

一、端口转发。
访问一个本地端口,实际上流量被转发到远程服务器的某个端口

ssh -L [local_addr:]local_port:remote_addr:remote_port [user@]sshd_addr
ssh隧道使用技巧
本地端口转发

技巧:ssh -f -N -L 可以使端口转发在后台运行。

二、访问一个本地端口,实际上流量被转发到中间的跳板机(公+私),再转发给远程服务器的某个端口

ssh -L命令允许将本地端口转发到任何机器上的远程端口,而不仅仅是 SSH 服务器本身。请注意remote_addrandsshd_addr可能具有或可能不具有相同的值。

ssh -L [local_addr:]local_port:remote_addr:remote_port [user@]bastion
ssh隧道使用技巧
本地端口转发给跳板机

三、想把机房里client服务器A(只有内外地址)的一个服务,通过gateway服务器B(有公网ip)的一个端口来被访问到。

我们可以称服务器B(有公网ip)为网关。命令如下:

ssh -R [remote_addr:]remote_port:local_addr:local_port [user@]gateway_addr

这里记住,要在Gateway端的sshd_config文件里添加一条:”GatewayPorts yes”
echo “GatewayPorts yes” >> /etc/ssh/sshd_config
想过sshd的配置参数,可以参考:https://linux.die.net/man/5/sshd_config#GatewayPorts

技巧:ssh -f -N -R ,可以使该命令在后台运行。

ssh隧道使用技巧

这个命令就是黑客常用的后门。

四、把第三步的本地服务再做一个延伸,即可以通过gateway访问到本地局域网的所有服务。

ssh -R [remote_addr:]remote_port:local_addr:local_port [user@]gateway_addr

命令和第三步是一样的,但是本地的local_addr变为了client的相同局域网的另外一个server的地址。

ssh隧道使用技巧
本地局域网的某个服务器端口被外网访问

总结:

1、命令中的local,是client自己,也可以client能访问的到的其他机器。
2、命令中的remote,是具有sshd server功能的服务器,或者sshd server 可以访问的到的机器,比如第二种跳板机的情况。
3、本地端口转发 ( ssh -L) 意味着client的ssh开启一个新端口用来提供被访问。
4、远程端口转发 ( ssh -R) 意味着远程的sshd开启一个新端口来提供被访问。
5、记忆技巧,”ssh -L local:remote” and “ssh -R remote:local” ,看到没有,总是从左侧开始一个新端口的监听。