autossh 內外網穿透配置

AutoSSH 能讓 SSH 隧道一直保持執行,他會啓動一個 SSH 進程,並監控該進程的健康狀況;當 SSH 進程崩潰或停止通信時,AutoSSH 將重啓動 SSH 進程

1.  安裝autossh

[root@localhost ~]# apt install autossh

2.  配置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:0GkZLmelyX6WVKK=============

將密鑰拷貝到遠程服務器上。假設ip:123.123.123.123

[root@localhost ~]# ssh-copy-id -i /root/.ssh/id_rsa.pub root@123.123.123.123

3. autossh的配置

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

爲查看內外網穿透是否成功,可通過netstat -atunp命令查看,成功效果如下:

4.可能存在的問題(隨時更新)

配置完AUTO SSH之後,發現還是無法穿透,解決方法是配置下ssh, 開啓 GatewayPorts 參數即可。

#修改配置

[root@localhost ~] vi /etc/ssh/sshd_config

GatewayPorts yes

#重啓SSHD

[root@localhost ~]  systemctl restart sshd.service 或者 sudo /etc/init.d/ssh restart

GatewayPorts原理:

當請求一個TCP端口的時候,默認情況下,SSH只監聽本機地址,這就導致AUTOSSH雖然穿透到阿里雲服務器,但是外網還是無法通過映射的端口 訪問局域網資源。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章