ssh反向隧道
摘要
通过ssh反向隧道和autossh实现从外网主机登录到内网主机
机器 | IP | 用户名 | 备注 |
---|---|---|---|
A | 192.168.142.142 | root | 内网主机 |
B | 47.93.39.196 | tunnel | 外网主机 |
B端外网主机操作
新建tunnel账号来管理登录主机
[root@localhost ~]#useradd tunnel \ #创建账号
[root@localhost ~]#passwd tunnel \ #设置密码
[root@localhost ~]#lsof -i:46578 \ #查看45678端口是否在使用,如无输出信息,表示该端口未使用。接下来在使用该端口来登录主机
A端内网主机操作
安装autossh
[root@localhost ~]# yum -y install autossh
在CentOS/RHEL 7以后,autossh不在是预编译包。所以你不得不从源码编译安装。
[root@localhost ~]# yum -y install wget gcc make
[root@localhost ~]# wget http://www.harding.motd.ca/autossh/autossh-1.4e.tgz
[root@localhost ~]# tar -xf autossh-1.4e.tgz
[root@localhost ~]# ./configure
[root@localhost ~]# make && make install
生成密钥(输入命令后一路回车)
[root@localhost ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
33:7a:d6:c3:25:95:8d:9a:86:9f:22:2e:6d:69:ae:50 root@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
| |
| + |
| + . |
| . + |
| E S = . |
| . . B + |
| . .o.+ * |
| ...=+ . . |
| .*o |
+-----------------+
将密钥复制到B端服务器
[root@localhost .ssh]# ssh-copy-id -i id_rsa.pub tunnel@47.93.39.196
tunnel@47.93.39.196's password:
Now try logging into the machine, with "ssh 'tunnel@47.93.39.196'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
创建开机启动脚本
[root@localhost ~]#vim /etc/rc.d/ssh.sh
#!/bin/bash
autossh -M 7777 -fNR 45678:loaclhost:22 tunnel@47.93.39.196
[root@localhost ~]#chmod +x /etc/rc.d/ssh.sh
[root@localhost ~]#sh /etc/rc.d/ssh.sh
参数说明:
-M : 在7777端口上监听连接的变化,只要断开就重连
-f :后台运行(PS:如果ssh免密登录未配置成功,不要加该参数)
-N :只建立连接,不打开shell(这个不知道对不对,加上就行了)
-R : 指定端口映射
45678:localhost:22
45678是外网主机的端口,必须是未在使用的
localhost本地主机
22本地ssh端口
tunnel@47.93.39.196 外网登录账号@外网登录IP地址
测试
##查看B端端口情况:
[root@jump chenyl]# lsof -i:45678
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
sshd 7024 tunnel 9u IPv4 893300 0t0 TCP localhost:eba (LISTEN)
##查看A端口端口情况:
[root@localhost ~]# lsof -i:7777
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ssh 31457 root 4u IPv6 175487 0t0 TCP localhost:cbt (LISTEN)
ssh 31457 root 5u IPv4 175488 0t0 TCP localhost:cbt (LISTEN)
##连接测试
B端--》A端
[tunnel@jump ~]$ ssh -p45678 root@localhost
The authenticity of host '[localhost]:45678 ([127.0.0.1]:45678)' can't be established.
RSA key fingerprint is da:04:4f:d5:bc:ab:5f:a7:9b:ce:56:30:ab:98:0b:0f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[localhost]:45678' (RSA) to the list of known hosts.
root@localhost's password:
Last login: Thu Aug 23 13:59:03 2018 from localhost
[root@localhost ~]#
成功!!!
如果想无密码登录到A端内网主机,将B端的公钥复制到A端的authorized_keys文件中(注意权限)