Subversion Repositories sysadmin_scripts

Rev

Blame | Last modification | View Log | Download | RSS feed

#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece;

# Configuration
my $target_ip = $ARGV[0] || '8.8.8.8';
my $log_file = '/var/log/ping_monitor.log';

# Validate IP address format
die "Usage: $0 <target_ip>\n" unless $target_ip;

# Run single ping test (suitable for cron)
my $timestamp = localtime->strftime('%Y-%m-%d %H:%M:%S');
my $ping_output = `ping -c 1 -W 2 $target_ip 2>&1`;

my ($status, $time_ms);

if ($ping_output =~ /time[=<](\d+\.?\d*)\s*ms/i) {
   $time_ms = $1;
   $status = 'SUCCESS';
} else {
   $time_ms = 'N/A';
   $status = 'FAILED';
}

# Extract packet loss if available
my $packet_loss = ($ping_output =~ /(\d+)% packet loss/) ? $1 : 'N/A';

# Log the result
open(my $fh, '>>', $log_file) or die "Cannot open $log_file: $!\n";
print $fh "$timestamp | IP: $target_ip | Status: $status | Time: ${time_ms}ms | Loss: ${packet_loss}%\n";
close($fh);

# Exit with appropriate status code
exit($status eq 'SUCCESS' ? 0 : 1);

Generated by GNU Enscript 1.6.5.90.