Pf and rf are the two final subroutines we need to discuss for our Ping Monitoring Over a WAN perl script. Both modules use the Net::Ping::External module, which we chose because it works on Windows and GNU/Linux (and because of this, probably works on most every platform that perl runs on). Here is the pf routine:
sub pf{ if(ping(hostname => $currentip, count => 10, size => 16, timeout => 3)){ return 0; } open (PM,">> mon.txt"); print PM "\n*************** Ping Fail : ".$currentserver." ***********\n"; close PM; return rf(); } |
We simply use the ping function to ping the hosts 10 times with a packet size of 16 bytes. We also set the timeout to 3 seconds. the ping function from the Net::Ping::External module returns true if the host is up, and false if the host is down. If the host is up, we return 0 (the ping did not fail). If the host is down, we then return the value of the rf subroutine:
sub rf{ $currentrouter=$currentip; $currentrouter=~s/(\d+\.\d+)(\.\d+\.)(\d+)/$1$2$3/; #Parse out the first two octets as $1, the third octet as $2, and the fourth octet as $3 #We need these to calculate the router to ping if($1 eq "10.40"){ $currentrouter=$1.".0.1"; } elsif($currentserver eq "pukey"){ $currentrouter="10.10.10.10"; } else{ $currentrouter=$1.$2."1"; } open (PM,">> mon.txt"); print PM "Ping failed... testing ".$currentserver." : ".$currentip." with router ".$currentrouter."\n"; printtime(); close PM; return (ping(hostname => $currentrouter, count => 10, size => 16, timeout => 3)); } |
The rf subroutine determines the appropriate router to test based on the host IP. It assumes the first 3 octets and tacks on .1, but it allows exceptions. You will have to edit this to suit your network. If the router is up, then the ping test will return true, which means that the entire ping test failed. Remember, we are only waking ourselves up if the host fails repeatedly and the WAN is not down.
For your pleasure, here is the complete script. Note that IE tries to render text files, so you might want to right-click, save-as, and then view.
Don’t rely on this script for production servers unless you know exactly what you are doing, and are sure that this script fits your needs. Do feel free to encorporate bits of the script as you need, or the whole script if you desire. Credit NetAdminTools.com, though, if you feel like it. 🙂 Please read our terms of use.
There are five parts to this article:
Introduction
Main Routine
Check/Log Routines
Adding Perl Mods
pf and rf routines
Related Post: Best Ping Monitoring Software