检查SSH隧道是否已启动并正在运行

Jar*_*und 6 linux perl telnet ssh-tunnel

我有一个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
Run Code Online (Sandbox Code Playgroud)

问题是目标$ 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);
}
Run Code Online (Sandbox Code Playgroud)

mik*_*ock 6

使用netcat - 通常nc在Linux系统上:

nc -dvzw10 ${HOSTNAME} 23
Run Code Online (Sandbox Code Playgroud)

对我有用,回复如下:

Connection to ${HOSTNAME} 23 port [tcp/telnet] succeeded!
Run Code Online (Sandbox Code Playgroud)

它也会在成功时返回0,并且对一个简单的连接感到满意,之后它就会消失.

  • -d表示不从键盘端读取任何内容
  • -v表示冗长(在脚本中将其关闭)
  • -z表示在建立连接后断开连接
  • -w10表示等待最多10秒,否则放弃