#!/usr/bin/perl -w # Run this perl code from cron every 5 minutes # Output from 'print' and 'die' will be sent to owner of the cron proc +ess by cron. use strict; use Net::Ping; use Net::SMTP; my $private_dir = "/tmp/ping_hosts_dir"; sub check_private_dir { # Used to prevent notify files from being crea +ted by non-superusers unless (-e $private_dir){ mkdir($private_dir, 0700) or die "Can't +mkdir $private_dir\n" } if (-d $private_dir) { my $mode = (stat($private_dir))[2]; if (-O $private_dir and ($mode == 040700)) { return } elsif (-O $private_dir and ($mode != 040700)) { chmod(0700, $private_dir); return; } else { die "We don't own $private_dir\n" } } else { die "$private_dir exists and is not a directory\n"; } } sub ping_hosts { my $ws; my $alive; my $count; my $timeout = 3; my @hosts = qw(host1 host2 host3 host4); # Following uses perl module Net::Ping to prevent spawning externa +l process my $ping_obj = Net::Ping->new("icmp"); foreach $ws (@hosts) { $alive = 0; $count = 5; while ($count > 0){ $alive += $ping_obj->ping($ws, $timeout); last if ($alive); $count--; } unless (-e "${private_dir}/${ws}.notify") { unless ($alive) { print "$ws did not respond to ping\n"; notify_admins($ws, "is_down"); } } elsif ($alive) { print "$ws is back up\n"; notify_admins($ws, "is_up"); } sleep(1); # To prevent flooding } $ping_obj->close(); # Redundant since open network conn is auto-cl +osed when leaving sub } sub notify_admins { # Called from ping_hosts() with host and changed s +tatus as arg my $ws = shift(@_); my $state = shift(@_); my $nfile = "${private_dir}/${ws}.notify"; my @admins = qw(8005551212@page.metrocall.com 8885551212@page.metr +ocall.com); my $message; if ( "$state" eq "is_down" ) { # Following replaces system(touch $nfile) to prevent spawning +external process open(NOTIFY, ">>$nfile") or die "Can't create notify file\n"; close(NOTIFY); $message = "$ws does not respond to ping\n"; } else { unlink ($nfile); $message = "$ws is back up\n"; } # Following replaces forking mailx to prevent spawning external pr +ocess # Note: Net::SMTP, part of the libnet collection of modules is not + part of standard pkg my $smtp = Net::SMTP->new('mailhost', HELLO => 'corp.com') or die +"Can't connect to mailhost for SMTP\n"; #$smtp->mail($ENV{USER}.'@corp.com'); $smtp->mail('root@corp.com'); $smtp->to(@admins); $smtp->data($message); $smtp->quit; } ### MAIN ### check_private_dir(); # Use $private_dir/hold.notify as a way of disabling notification durr +ing controlled reboots ping_hosts() unless (-e "$private_dir/hold.notify");
In reply to Ping host was Re: lock files vs. non-predictable file names
by RuphSkunk
in thread lock files vs. non-predictable file names
by RuphSkunk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |