Shell-Script
編寫腳本來檢查 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。
你可以用
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").