一、介绍
Autossh 是一个用于建立和维护 SSH 隧道的工具,它在网络连接断开或中断时可以自动重新连接。通过 Autossh,您可以方便地在不稳定的网络环境下保持持久的 SSH 连接。
Autossh 是一个跨平台的工具,可在多个操作系统上使用,包括 Linux、Unix 和 macOS。它提供了简单而有效的方法来管理 SSH 隧道,并确保持久的、安全的连接。
请注意,Autossh 是一个独立的工具,与 SSH 客户端本身无关。您仍然需要安装和配置 SSH 客户端来进行身份验证和建立初始的 SSH 连接。
缺陷:目前只支持代理TCP端口。
二、环境
IP | 环境 | 作用 |
---|---|---|
23.183.84.76 | 云服务器 | 外网服务器通过云服务器访问内网资源 |
192.168.2.101 | 内网服务器 | 映射端口到云服务器上 |
三、部署
云服务器操作
## 修改ssh参数
[root@localhost ~]# vim /etc/ssh/sshd_config
## 修改下面参数
连接超时及转发相关:
GatewayPorts yes
TCPKeepAlive yes
ClientAliveInterval 60
ClientAliveCountMax 3
证书相关:
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
## 重启ssh服务
[root@localhost ~]# systemctl restart sshd
内网服务器操作
## 安装autossh
[root@localhost ~]# yum -y install autossh## 免密钥登入云服务器
[root@localhost ~]# ssh-keygen -t rsa //一直回车## 上传云服务器
[root@localhost ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub -p 22 root@23.183.84.76
## 端口代理
[root@localhost ~]# autossh -p 22 -M 11222 -fNR 11221:localhost:22 root@23.183.84.76
(将内网服务器22端口映射到云服务器11221端口,云服务器ssh端口22,云服务器11222端口为监听状态端口)-p 22:指定SSH服务器的端口号。默认情况下,SSH使用22端口
-M 11222:指定Autossh使用的监测端口号。Autossh会在指定的端口上建立一个本地监听器,用于监测SSH连接的状态。请确保此端口未被其他应用程序占用。
-f: 在后台运行Autossh。
-NR 11221:localhost:22: 进行远程端口转发。此参数将远程服务器上的11221端口转发到本地计算机的SSH服务(默认端口 22)上。这样,您可以通过连接远程服务器的 11221 端口来访问本地计算机的 SSH 服务。
开机自启动
[root@localhost ~]# vim /etc/rc.d/rc.local
## 末尾添加
autossh -p 22 -M 11222 -fNR 11221:localhost:22 root@23.183.84.76[root@localhost ~]# chmod +x /etc/rc.d/rc.local
通过互联网服务器访问内网服务器
ssh -p 11221 root@23.183.84.76 (需要输入内网服务器的密码)