【问题标题】:Checking if an SSH tunnel is up and running检查 SSH 隧道是否已启动并正在运行
【发布时间】:2012-09-18 06:48:33
【问题描述】:

我有一个 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 对我没有帮助,因为隧道的远端通常是正常的,但丢包率非常高

已解决:根据 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);
}

【问题讨论】:

  • 由于您使用的是Net::Telnet 模块,您是否尝试过使用open 调用并测试是否成功?我不是 Telnet 专家,但如果是我,我可能会尝试这样做......
  • 如果没有简单的测试方法,我可能会这样做:如果 time_spend_trying

标签: linux perl telnet ssh-tunnel


【解决方案1】:

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

nc -dvzw10 ${HOSTNAME} 23

对我有用,回复如下:

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

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

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

【讨论】:

    【解决方案2】:

    您可以将 ping 集成到您的 ssh 服务器,如果它工作正常,则 ssh 隧道已启动

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

    【讨论】:

    • ping 对我没有多大帮助,因为它通常有大约 50% 的丢包率(这是事先测试过的,信不信由你,低至 50% 是可以接受的)
    • 但如果隧道启动,它会成功退出。质量是其他沟通水平的一部分
    • 如果您想要更好的等待质量,您可以解析 ping 输出。但是如果质量太差,你会断开连接吗?
    【解决方案3】:

    我认为 fping 可能比通常的 ping 更好,对脚本更友好。

    fping -t 60000 [你的服务器]

    应该在放弃前 60 秒尝试连接到服务器 像

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

    我认为即使编码不是真实的,您也能理解。

    【讨论】:

      猜你喜欢
      • 2011-01-01
      • 2020-09-11
      • 1970-01-01
      • 2011-07-10
      • 2017-07-15
      • 2021-04-09
      • 2013-09-23
      • 2022-01-25
      • 1970-01-01
      相关资源
      最近更新 更多