| 190 |
rodolico |
1 |
#!/usr/bin/perl
|
|
|
2 |
use strict;
|
|
|
3 |
use warnings;
|
|
|
4 |
use Time::Piece;
|
|
|
5 |
|
|
|
6 |
# Configuration
|
|
|
7 |
my $target_ip = $ARGV[0] || '8.8.8.8';
|
|
|
8 |
my $log_file = '/var/log/ping_monitor.log';
|
|
|
9 |
|
|
|
10 |
# Validate IP address format
|
|
|
11 |
die "Usage: $0 <target_ip>\n" unless $target_ip;
|
|
|
12 |
|
|
|
13 |
# Run single ping test (suitable for cron)
|
|
|
14 |
my $timestamp = localtime->strftime('%Y-%m-%d %H:%M:%S');
|
|
|
15 |
my $ping_output = `ping -c 1 -W 2 $target_ip 2>&1`;
|
|
|
16 |
|
|
|
17 |
my ($status, $time_ms);
|
|
|
18 |
|
|
|
19 |
if ($ping_output =~ /time[=<](\d+\.?\d*)\s*ms/i) {
|
|
|
20 |
$time_ms = $1;
|
|
|
21 |
$status = 'SUCCESS';
|
|
|
22 |
} else {
|
|
|
23 |
$time_ms = 'N/A';
|
|
|
24 |
$status = 'FAILED';
|
|
|
25 |
}
|
|
|
26 |
|
|
|
27 |
# Extract packet loss if available
|
|
|
28 |
my $packet_loss = ($ping_output =~ /(\d+)% packet loss/) ? $1 : 'N/A';
|
|
|
29 |
|
|
|
30 |
# Log the result
|
|
|
31 |
open(my $fh, '>>', $log_file) or die "Cannot open $log_file: $!\n";
|
|
|
32 |
print $fh "$timestamp | IP: $target_ip | Status: $status | Time: ${time_ms}ms | Loss: ${packet_loss}%\n";
|
|
|
33 |
close($fh);
|
|
|
34 |
|
|
|
35 |
# Exit with appropriate status code
|
|
|
36 |
exit($status eq 'SUCCESS' ? 0 : 1);
|