Home > Bash, perl, Programming, Uncategorized > check host is alive or not with perl Net::Ping

check host is alive or not with perl Net::Ping

With Bash

#!/usr/bin/bash
chost() {
    up=`ping -c 1 -W $2 $1|grep 100%`
    return `test -z "$up"`
}
[ $# -lt 1 ] && "Usage is: $0 host [timeout=5]" && exit 1
[ $# -gt 1 ] && timeout=$2 || timeout=5
chost $1 $timeout && echo "$1 is alive"

Problem with this script:
If the default route is missing when running this script to test an external host, the result will show the host is alive, along with the following ping error:
connect: Network is unreachable

Hence the (improved) version of ping script with Perl:

With Perl

#!/usr/bin/perl -w
use Net::Ping;
use Switch;

if (@ARGV >1) { $host=$ARGV[0]; $timeout=$ARGV[1]; }
elsif (@ARGV>0) { $host=$ARGV[0]; $timeout=5; }
else { print "Usage is: $0 host <timeout=5>\n"; exit; }

$p=Net::Ping->new('icmp');
print "$host is alive.\n" if $p->ping($host, $timeout);
$p->close();

Embed perl in bash

I found it quite handy to use the above perl script in some of my gateway management bash scripts.

#!/bin/bash
chost() {
export host=$1
export timeout=$2
a=`perl -MNet::Ping -e '$p=Net::Ping->new('icmp'); \
   if( $p->ping($ENV{'host'},$ENV{'timeout'}) ) \
           {print "OK";} \
   else {print "BAD";} \ 
   $p->close();'`
return `test $a == "OK"`
}
[ $# -lt 2 ] && echo "Usage is: $0 host timeout" && exit 0
chost $1 $2 && echo "good" || echo "not good"

Advertisements
  1. poisonbit
    December 30, 2009 at 10:04 pm

    Nice post. You could too complete the script in perl, whitout bash:

    
    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use Net::Ping;
    
    my $host    = $ARGV[0] or print "Usage is: $0 host [timeout]\n" and exit 1;
    my $timeout = $ARGV[1] || 5;
    my $pinger  = Net::Ping->new('icmp', $timeout);
    
    if ($pinger->ping($host)) {
        print "good\n";
    }else{
        print "not good, timeout of $timeout seconds reached\n";
    }
    

    And of course could be elegant to extend it with input validation ¿host is a IP(v4) address?¿time is a non negative integer? before use $pinger :)

    • ricoch3n
      December 31, 2009 at 11:12 pm

      The way you assign $host and $timeout is pretty neat. I started learning Perl recently while reading “Mastering Regular Expressions”. Thanks for sharing.

  2. pavel
    September 21, 2011 at 1:28 pm

    icmp ping requires root privilege at test.pl line 15
    just under root …

  3. Michael
    July 16, 2012 at 7:43 am

    Is it possible to modify your script to ping forever ?

    • July 16, 2012 at 4:24 pm

      I am not sure why you would want to do that but it’s totally possible, just wrap the body of the script inside a FOR or WHILE loop (and add some sleep time at the end of each loop) should do it.

  4. dhruti
    January 16, 2013 at 5:42 pm

    #!/usr/bin/perl -w
    #use strict;
    use Net::Telnet;

    use Net::ping;
    $telnet = new Net::Telnet(Timeout=>30, Errmode=>’die’,port =>23**); #creating connection
    open $inputLog, “>1010.log”; #creating file with name 10100269wire

    $telnet->open(‘10.100.2.**’); #creating connection for this IP
    #$telnet->waitfor(‘/login: $/i’);
    #$telnet->print(‘admin’);

    $telnet->waitfor(‘/password: /i’); # here if i enter password
    $telnet->print(‘system’); #this the password for ip 10.100.
    $telnet->input_log($inputLog); #here data will input session log in file which we created 1010wire.log

    #$telnet -> print(“who”);

    #@lines = $telnet->cmd(‘ps -ef’);

    $telnet->waitfor(sleep);

    print ” hello”;
    #$telnet->close();
    #sleep;

    yes my script is running for one week i am able to make telnet session. now during this session i want to check ping ip -t to check status that session is still running or with some reason ip is disconnected or rebooted than it prints the message that ‘request time out’ and then i want to sleep this for some time limit to again reconnect the session and again start data in dump file with append option please help me how should i do this it is urgent and need some action on it…

    • January 21, 2013 at 12:37 am

      dhruti,
      First of all the scripts I wrote for this post is for checking if hosts is up or down, what you wanted to achieve is to check if telnet session is still valid or not. I am not familiar with Net::Telnet but if your purpose is to get the ps -ef command output from the remote host, you might want to try with this simple technique: http://linux.byexamples.com/archives/258/when-netcat-act-as-telnet-client-it-becomes-better/

      Also regarding the 2nd requirement – continuous monitoring, you don’t really need looping and sleeping to get the job done, simply write a bash script with the above nc trick and run it with crontab. Have crontab send yourself an email if something goes wrong (like the host is down or telnet is not running) by setting the MAILTO variable in your crontab jobs, see http://www.cyberciti.biz/faq/linux-unix-crontab-change-mailto-settings/

      Good luck!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: