Perl - 如何使用 Ping 检查服务器是否在线?

Perl - How to check if a server is live using Ping?

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

#!/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';
}

代码应该可以工作(我认为)。但是对于每台服务器,每次都会失败(returns "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
$ ping -c 3 google.com

这是在执行 ICMP ping。

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

不是 执行 ICMP ping。来自 the documentation:

You may choose one of six different protocols to use for the ping. The "tcp" protocol is the default. ... With the "tcp" protocol the ping() method attempts to establish a connection to the remote host's echo port.

echo 服务今天几乎从未激活或端口被阻止,因此使用它作为端点通常不起作用。如果您改为使用 Net::Ping 执行 ICMP ping,它的工作方式与使用 ping 命令时相同:

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

请注意,其中的 none 非常适合确定主机是否已启动。 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')) { ...