簡體   English   中英

檢查SSH隧道是否已啟動並正在運行

[英]Checking if an SSH tunnel is up and running

我有一個perl腳本,當有點蒸餾時,看起來像這樣:

my $randport = int(10000 + rand(1000));          # Random port as other scripts like this run at the same time
my $localip = '192.168.100.' . ($port - 4000);   # Don't ask... backwards compatibility
system("ssh -NL $randport:$localip:23 root\@$ip -o ConnectTimeout=60 -i somekey &");    # create the tunnel in the background

sleep 10;       # Give the tunnel some time to come up

# Create the telnet object
my $telnet = new Net::Telnet(
        Timeout =>      10,
        Host    =>      'localhost',
        Port    =>      $randport,
        Telnetmode =>   0,
        Errmode =>      \&fail,
);

# SNIPPED... a bunch of parsing data from $telnet

問題是目標$ ip是在帶有非常不可預測的帶寬的鏈路上,因此隧道可能會立即出現,可能需要一段時間,它可能根本不會出現。 因此需要睡眠才能讓隧道有一段時間起床和跑步。

所以問題是:我如何測試隧道是否啟動並運行? 如果隧道立即出現,10秒是非常不希望的延遲。 理想情況下,我想檢查它是否已經啟動並繼續創建telnet對象,最多為30秒。

編輯: Ping不能幫助我mouch,因為隧道的遠端通常是up,但是有很多的數據包損失

解決:根據mikebabcock建議的提示推斷, sleep 10已經被這個像魅力的塊所取代:

my $starttime = time();
while (1)
{
    # Check for success
    if (system("nc -dzw10 localhost $randport > /dev/null") == 0) { last }

    # Check for timeout
    if (time() > $starttime + 30) { &fail() }

    # 250ms delay before recheck
    select (undef, undef, undef, 0.25);
}

在Linux系統上使用netcat - 通常是nc

nc -dvzw10 ${HOSTNAME} 23

對我有用,回復如下:

Connection to ${HOSTNAME} 23 port [tcp/telnet] succeeded!

它也會在成功時返回0,並且對一個簡單的連接感到滿意,之后它就會消失。

  • -d表示不從鍵盤端讀取任何內容
  • -v表示冗長(在腳本中將其關閉)
  • -z表示在建立連接后斷開連接
  • -w10表示等待最多10秒,否則放棄

您可以將ping集成到您的ssh服務器,如果它正常工作,則ssh隧道已啟動

# only a ping sample :-D
if !  ping -c 1 192.168.101.9
then
        echo ":-("
else
        echo ":-)"
fi

我認為fping可能比通常的ping更好,腳本更友好。

fping -t 60000 [你的服務器]

應該嘗試在放棄之前60秒連接到服務器

if(fping -t 60000 [your server]) {
execute desired code;
} else {
execute this script again to rerun;;
}

即使編碼不真實,我認為你也能得到這個想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM