Blog
Blog copied to clipboard
autossh内外网穿透方法
场景
1、操作系统: CentOS 7.4
2、资源:
- 内网服务器:1台
- 阿里云服务器:1台
- 公网IP:123.123.123.123
3、目标: 实现外网穿透到局域网的服务器,访问服务器的后台系统。
4、解决方法:内网服务器通过autossh,与公网服务器之间建立稳定的端口映射关系。
具体的步骤如下:
配置SSH免密登录
[root@localhost ~]# ssh-keygen
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:
SHA256:0GkZLmelyX6WVKKF7k4eQ16FMK1G9G9m96NQJkG/y18 [email protected]
The key's randomart image is:
+---[RSA 2048]----+
| .=++o. |
| +o%+oo |
| oo&.oo . |
| B=..o. . |
| =S.+.=+. |
| *o +=... |
| + o . o .E|
| o . o o|
| . . |
+----[SHA256]-----+
[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]
安装AUTOSSH
安装AUTOSSH
[root@localhost ~] wget http://www.harding.motd.ca/autossh/autossh-1.4e.tgz
[root@localhost ~] gunzip -c autossh-1.4e.tgz | tar xvf -
[root@localhost ~] cd autossh-1.4e
[root@localhost autossh-1.4e] ./configure
[root@localhost autossh-1.4e] make & make install
配置AUTOSSH
[root@localhost ~] autossh -M 5678 -NR 1234:localhost:8080 -f [email protected]
备注:
-
5678
端口:负责通过这个端口监视连接状态,连接有问题时就会自动重连 -
1234
端口:远程服务器的端口 -
localhost:8080
: 本地或内网IP地址、端口 -
-f
: 后台运行
如果想要断开AUTOSSH的隧道连接,只需要把 AUTOSSH监听端口的进程 kill 掉就可以了:
[root@localhost ~]# netstat -apn | grep 5678
tcp 0 0 127.0.0.1:5678 0.0.0.0:* LISTEN 8843/ssh
tcp6 0 0 ::1:5678 :::* LISTEN 8843/ssh
[root@localhost ~]# kill -9 8843
如果想同时开多个隧道,则 AUTOSSH的监听端口必须也开多个,监听端口不能一样。
修改sshd配置
配置完AUTO SSH之后,发现还是无法穿透,解决方法是配置下ssh, 开启 GatewayPorts
参数即可。
#修改配置
[root@localhost ~] vi /etc/ssh/sshd_config
GatewayPorts yes
#重启SSHD
#CentOS 7
[root@localhost ~] systemctl restart sshd.service
#CentOS 6
[root@localhost ~] /etc/init.d/sshd restart
GatewayPorts原理:
当请求一个TCP端口的时候,默认情况下,SSH只监听本机地址,这就导致AUTOSSH虽然穿透到阿里云服务器,但是外网还是无法通过映射的端口 访问局域网资源。
When you forward a TCP port (either locally or remotely), by default SSH only listens for connections to the forwarded port on the loopback address (localhost, 127.0.0.1).