autossh内外网穿透方法

@johnnian 2018-01-11 09:50:57发表于 johnnian/Blog Linux

场景

资源: 内网服务器1台、公网服务器1台、公网域名1个

在公司内网搭建的服务后台,客户端需要远程联调,并且客户端访问后台必须是以 HTTPS 的形式访问。

可以通过下面的方式解决:

  • 内网服务器通过autossh,与公网服务器之间建立稳定的端口映射关系;
  • 客户端与公网服务器,通过 NginxLet's Encrypt, 建立HTTPS链接(可以参考Nginx配置多个HTTPS域名这篇文章);
  • Nginx收到HTTPS请求后,脱去安全认证,转发到与内网映射的端口上;

配置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 root@localhost.localdomain
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 root@123.111.111.111

安装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 root@123.111.111.111

备注:

  • 5678 端口:负责通过这个端口监视连接状态,连接有问题时就会自动重连
  • 1234 端口:远程服务器的端口
  • localhost:8080: 本地或内网IP地址、端口
  • -f : 后台运行

备注