Doing Many Things, Like pings
Randal L. Schwartz As a UNIX systems administrator, Im often faced with those little mundane tasks that seem so trivial to me but so important to the community Im supporting. Little things like hey, is that host up and responding to pings?. Such tasks generally have a very repetitive nature to them, and scripting them seems to be the only way to have time to concentrate on the tasks that really need my attention.
Lets look at the specific task of pinging a number of hosts on a subnet. Now, there are tools to do this quickly (like nmap), and there are even Perl modules to perform the ping (as in Net::Ping), but I wanted to focus on something familar that can be launched from Perl as an external process, and the system C<ping> command seems mighty appropriate for that.
First, lets look at how to ping one host, on my BSD-ish system:
sub ping_a_host {
my $host = shift;
'ping -i 1 -c 1 $host 2>/dev/null' =~ /0 packets rec/ ? 0 : 1;
}
Here, Im firing up a subshell to execute the ping -i 1 -c 1 command, which on my system requests that ping have a 1-second timeout, and selects (as Sean Connerys character so eloquently said in The Hunt for Red October) one ping only. Your ping parameters may vary: check your manpage.
The output is scanned for the string 0 packets rec, which if absent means we got a good ping. So if the match is found, we return 0 (the ping was bad); otherwise, well return 1. The ping command spits out some diagnostics on standard error, which well toss using Bourne-shell syntax.
Note that the value of $host is not checked here for sanity. We certainly wouldnt want to accept a random command-line parameter or (gasp) a Web form value here without some serious validation.
|