マシン生存確認
Net::Pingモジュールを使うと簡単です。
# TCPで確認
use strict;
use warnings;
use Net::Ping;
my $host = 'www.example.com';
my $timeout = 5;
my $port = 80;
my $p = Net::Ping->new("tcp");
$p->{port_num} = $port;
if ($p->ping($host, $timeout)) {
print "$host:$port is alive\n";
} else {
print "$host:$port is not alive\n";
}
# ICMPで確認
use strict;
use warnings;
use Net::Ping;
my $host = 'www.example.com';
my $timeout = 5;
my $p = Net::Ping->new("icmp");
if ($p->ping($host, $timeout)) {
print "$host is alive\n";
} else {
print "$host is not alive\n";
}
ICMPで確認する場合Net::Pingではroot権限が必要になります。一般ユーザで実行する場合はNet::Ping::Externalを使います。
use strict;
use warnings;
use Net::Ping::External;
my $host = 'www.example.com';
my $timeout = 5;
my $is_alive = Net::Ping::External::ping(
host => $host, timeout => $timeout);
if ($is_alive) {
print "$host is alive\n";
} else {
print "$host is not alive\n";
}
