【问题标题】:Perl - How to check if a server is live using Ping?Perl - 如何使用 Ping 检查服务器是否处于活动状态?
【发布时间】:2020-04-11 16:51:55
【问题描述】:

我在 Linux 上使用 Perl 5,版本 30。我想检查服务器是否处于活动状态,并且我只对 ping 调用返回 true 或 false 感兴趣。这是我的(非工作)代码:

#!/usr/bin/perl
use strict;
use warnings;

use Net::Ping;
my $pinger = Net::Ping->new();
if ($pinger->ping('google.com')) {
   print 'alive\n';
} else {
   print 'dead\n';
}

代码应该可以工作(我认为)。但是每次都会对每个服务器都失败(返回“dead”)。如果我以 sudo 执行它也会失败:sudo perl pingcheck.pl。 (编辑:我不能在实践中使用 sudo。我尝试它只是为了排除故障。)

我确实安装了Net::Ping

$ cpan -l | grep Net::Ping
Net::Ping       2.71

没有来自 Perl 的错误消息。

如果我在 bash 中做同样的事情,ping 会按预期工作:

$ ping -c 3 google.com
PING google.com (64.233.178.100) 56(84) bytes of data.
64 bytes from ol-in-f100.1e100.net (64.233.178.100): icmp_seq=1 ttl=43 time=49.8 ms
64 bytes from ol-in-f100.1e100.net (64.233.178.100): icmp_seq=2 ttl=43 time=49.8 ms
64 bytes from ol-in-f100.1e100.net (64.233.178.100): icmp_seq=3 ttl=43 time=50.0 ms

--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 49.754/49.846/50.011/0.116 ms

【问题讨论】:

    标签: perl tcp connection port ping


    【解决方案1】:
    $ ping -c 3 google.com
    

    这是在进行 ICMP ping。

    my $pinger = Net::Ping->new();
    if ($pinger->ping('google.com')) { ...
    

    不是在进行 ICMP ping。来自the documentation

    您可以从六种不同的协议中选择一种用于 ping。 “tcp”协议是默认协议。 ... 使用“tcp”协议,ping() 方法会尝试建立到远程主机的回显端口的连接

    echo 服务现在几乎从不活跃或端口被阻塞,因此使用它作为端点通常不会工作。如果您改为使用 Net::Ping 执行 ICMP ping,它的工作原理与使用 ping 命令一样:

    my $pinger = Net::Ping->new('icmp');
    if ($pinger->ping('google.com')) { ...
    

    请注意,这些都不适合确定主机是否已启动。 ICMP ping 经常被阻止。相反,您应该检查是否可以连接到您要使用的特定服务:

    # check if a connect to TCP port 443 (https) is possible
    my $pinger = Net::Ping->new('tcp');
    $pinger->port_number(443); 
    if ($pinger->ping('google.com')) { ...
    

    【讨论】:

    • 我不能使用 ICMP ping 协议,因为这需要 sudo(来自文档)。但是,使用特定 TCP 端口的最后一个选项看起来很有趣。我会试试看,如果可行,我会接受你的回答。
    • 使用 TCP 和特定端口确实有效。已接受答案。
    猜你喜欢
    • 2021-07-23
    • 2013-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 2019-12-10
    相关资源
    最近更新 更多