eldestructo has asked for the wisdom of the Perl Monks concerning the following question:

I've never tried to write a monitoring script before, but thought I would give it a go. This is what I have so far:
#!/usr/bin/perl # # unless($ARGV[0] && $ARGV[1] && $ARGV[2]) { print "Please supply the following information:\n"; print "ping-test.pl <host address> <notification sensitivity> +<email address>.\n"; exit; } while (1) { &monitor; } sub monitor { use Net::Ping; $sendmail="/usr/sbin/sendmail"; $host=$ARGV[0]; $sensitivty=$ARGV[1]; $email=$ARGV[2]; $p = Net::Ping->new("icmp", 2); $up=$p->ping($host); $p->close(); if ($up) { print "Host $host alive.\n"; $count{$_}=0; } else { $count{$_}++; print "$count{$_}\n"; if ($count{$_} eq $sensitivty) { print "Server is down - notifying admin at $em +ail\n"; # open (MAIL,"|$sendmail -t -f \"$email\""); # print MAIL "To: $email\n"; # print MAIL "From: $email\n"; # print MAIL "Subject: Server down\n"; &recheck; } } } sub recheck { if ($up) { $recovered{$_}++; if ($recovered{$_} eq $sensitivty) { print "Notifying admin at $email of recovery.\ +n"; # open (MAIL,"|$sendmail -t -f \"$email\""); # print MAIL "To: $email\n"; # print MAIL "From: $email\n"; # print MAIL "Subject: Server down\n"; $recovered{$_}=0; $count{$_}=0; } else { $count{$_}++; print "Still trying to recover.\n"; } } }
I know it is probably really ugly :) But basically I am trying to get it to send out a recovery email too and then start all over, but it has failed so far. It seems to work up until the call to &recheck, maybe I am going about it the wrong way. Thanks for any help

Replies are listed 'Best First'.
Re: Perl question, icmp script.
by GrandFather (Saint) on Apr 12, 2006 at 08:18 UTC

    This code is so muddled that, even though the sub names indicate what is wanted in general, the details are completely opaque.

    You might like to explain why you need hashes for count and recovered. It is unusual to use eq for numeric comparisons and bad practice to use an equality test on numeric values when >= or <= are safer (and may fix some of your troubles in this case).

    You should always place use strict; use warnings; at the start of your Perl scripts. They do no harm and can save you a lot of grief!

    You could replace the Ping with a ReadKey (see Term::ReadKey) to make debugging easier and to make it easier for others to reproduce your results.


    DWIM is Perl's answer to Gödel
Re: Perl question, icmp script.
by Marza (Vicar) on Apr 12, 2006 at 18:29 UTC

    GrandFather has covered it pretty well.

    Might I suggest you take a look at the tutorials and the code catacombs for some examples on "friendlier" code?