ssh 隧道应用&代理
一般情况
user ---> 跳板机 ----> 服务器1
user 可以ssh连接跳板机,但是不能直接连接服务器1。服务器1只能通过跳板机连接。
这是比较通常的堡垒机的情况。
一般情况user是先ssh登陆到跳板机,再从跳板机 ssh 到 服务器1
ssh两次。而且要从user本地scp文件到服务器1,也要ssh两次。或是用lrzsz 方式。
最佳的解决办法就是用ssh隧道 。隧道建立以后user 可以直接ssh到服务器1
第一种
编辑/etc/ssh/ssh_config
在最后添加
Host jumphost
HostName 1.1.2.3
User xxx
IdentityFile ~/.ssh/xxx.pem
Host server1
Hostname 172.21.89.20
ProxyCommand ssh -q -W %h:%p jumphost
User xxx
IdentityFile ~/.ssh/xxx.pem
添加好后,直接 ssh server1 就能正常连接到server1服务器。
原理就是连接ssh server1 之前,先ssh 到 jumphost 。然后通过这个连接再ssh server1。
还有一种
先执行
ssh -qNfCD 0.0.0.0:1080 xxx@jumphost
运行这个命令以后,本地回监听1080端口
在ssh_config 里
Host server1
Hostname 172.21.89.20
ProxyCommand connect-proxy -S 127.0.0.1:1080 %h %p
User xxx
IdentityFile ~/.ssh/xxx.pem
ssh server1 就可以直接连接到server1
这个原理就是 ssh 到jumphost 并且监听本地1080端口
将ssh server1 数据通过connect-proxy 这个命令转发到本地的127.0.0.1:1080 转发过去。
这个办法也可以做多个机器串联。
user ---> jumphost1 ----> jumphost2 --- server1
user必须通过jumphost1连接到jumphost2 再连接到server1
Host jumphost2
HostName 3.2.3.2
User xxx
ProxyCommand ssh -q -x -W %h:%p jumphost1
IdentityFile ~/.ssh/xxx.pem
ServerAliveInterval 60
Compression yes
Host jumphost1
HostName 1.1.1.2
User xxx
IdentityFile ~/.ssh/xxx.pem
ServerAliveInterval 60
Compression yes
Host server1
Hostname 2.2.2.3
ProxyCommand ssh -q -W %h:%p jumphost2
User xxx
IdentityFile ~/.ssh/xx.pem
ServerAliveInterval 60
Compression yes
多说一句 connect-proxy 直接用epel 安装就行。如果是centos6 ,可以使用nc ,没有就是yum install -y netcat 安装一个。
ProxyCommand nc -X 5 -x 127.0.0.1:1080 %h %p
注意centos7 不能用nc 了 。因为centos7装的nc 没有-X 这个参数。只能用connect-proxy