Friday, 6 January 2017

A Ping check script in Perl

The title sounds simple. The script sounds like a mere one liner. To just ping a server ?
The task is simple but the way we execute it in the script I wish to share isn't simple.
I took the ping check as a basic example to demonstrate the concept.

I have a list of servers. I need to separate them. The list of servers which respond to a ping to go in one file & the servers which do not respond to a ping go in another file.
The list of servers which will be used as input will be supplied as a command line argument & read in the script via @ARGV.
The script will exit if not file is provided as a command line argument.

Here is the script:

[root@alive ~]# cat ssh.pl
#!/usr/bin/perl
#

$#ARGV += 1;
my $list = $ARGV[0] ;

if ($#ARGV == 0) {
        print "script usage: $0 \<server_list\> \n";
        exit ;
        }

open (FH1, "$list") || die "error in file $list : $!" ;
open (FH2, ">> host_alive") || die "errors $!" ;
open (FH3, ">> host_dead") || die "errors $!" ;

while (<FH1>) {
        chomp $_ ;
        my $output = `ping -c 1 $_ &> /dev/null`;
        print  "$output \n" ;
        if ($? == 0) {
                printf FH2 "$_ \n"  ;
                }
        else    {
                printf FH3 "$_ \n" ;
                }
        }

print "script complete \n" ;

I've put some host names in a file named server_list.

[root@alive ~]# cat server_list
test
alive
test123
alive

Now, lets test the script by typing: ./ssh.pl server_list
Once the script completes the content within my two output files is as follows:


[root@alive ~]# cat host_alive
alive
alive
[root@alive ~]# cat host_dead
test
test123
[root@alive ~]#


So, the concept I've tried to explain here is how we can use a given list of systems & classify a server based on it's output response to a command.
Many would argue that the script would be much simpler in bash but I've made an effort to appreciate the beauty in complexity.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...