Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2002 > May

Doing Many Things, Like pings

Randal L. Schwartz

As a UNIX systems administrator, I’m often faced with those little mundane tasks that seem so trivial to me but so important to the community I’m 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.

Let’s 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, let’s 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, I’m 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 Connery’s 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, we’ll return 1. The ping command spits out some diagnostics on standard error, which we’ll toss using Bourne-shell syntax.

Note that the value of $host is not checked here for sanity. We certainly wouldn’t want to accept a random command-line parameter or (gasp) a Web form value here without some serious validation.




MarketPlace

�Six Sigma� Certified?
100% Online-Six Sigma Certificate From Villanova -Find Out More Now.

Project Management-Online
Nation's Leading Online PMP Course From Villanova-Find Out More Now.

Flowcharts from C/C++ code -- Free trial download
Understand C/C++ code in less time. A new team member ? Inherited legacy code ? Get up to speed faster with Crystal Flow for C/C++. Code-formatting improves readability. Flowcharts are integrated with code browser. Export flowcharts to Visio.

Automate Software Builds with Visual Build Pro
Easily create an automated, repeatable process for building and deploying software.

Wanna see your ad here?