編寫腳本來檢查 ssh 隧道是否打開

編寫腳本來檢查 ssh 隧道是否打開

我的 ssh 隧道設定如下:

ssh -N -L 1105:remote.server:25 office-machine&

我想編寫一個腳本來設定一個檢查,比如說每分鐘一次(也許我可以使用 cron 作業來完成),它將檢查此連接是否已建立,否則它將建立連接(如果 VPN 已開啟) )。

我該如何執行 ssh 隧道檢查?

提前致謝。

PS:我試過了

autossh -N -L 1105:remote.server:25 office-machine&

但它退出了。我懷疑選項是正確的。事實上,線上幫助頁/幫助表明沒有 -N 和 -L 選項,而只有 -f 和 -M。

答案1

您可以用於autossh此用途。引用Ubuntu 線上說明頁:

 autossh is a program to start a copy of ssh and monitor it, restarting it as necessary
 should it die or stop passing traffic.

 The original idea and the mechanism were from rstunnel (Reliable SSH Tunnel). With version
 1.2 of autossh the method changed: autossh uses ssh to construct a loop of ssh forwardings
 (one from local to remote, one from remote to local), and then sends test data that it
 expects to get back. (The idea is thanks to Terrence Martin.)

因此必須指定一個額外的監控連接埠autossh。選擇一些連接埠 N,使 N 和 N+1 都空閒,並將其與選項一起使用-M,例如,

autossh -M 20000 -N -L 1105:remote.server:25 office-machine

您也可以使用 停用監控-M 0。在基於 Debian 的系統上,autossh可以自動選擇一個空閒連接埠進行監控。


如果您的 VPN 連線中斷,autossh應透過監控連接埠偵測到 SSH 連線不再有效,然後嘗試重新啟動它。在那之後:

Continued failures
 If the ssh connection fails and attempts to restart it fail in quick succession, autossh
 will start delaying its attempts to restart, gradually backing farther and farther off up to
 a maximum interval of the autossh poll time (usually 10 minutes).  autossh can be "prodded"
 to retry by signalling it, perhaps with SIGHUP ("kill -HUP").

相關內容