Monday, 14 October 2013

Well, someone may call this foolish as one can simply ping the host to check whether it is up or not. Still, this script is for them who like making simple things more complex.

Here we go!

As we are checking whether a host is up or not, we need to take input from the user which will be the target host that the user wants to test if it is up or not. We would need a variable to store the name of this target host, say it will be '$target'.

So, we have the host to be tested in a variable called '$target'. Now the main part of our logic. We will send an ICMP packet to the target host and we will receive ICMP reply from the host if it is alive and we would save the number of such replies received in a variable, say '$count'. If we get any reply from the target host, we will print "Yes! Host is Alive!", else "Host is not Alive! Try Again Later..".

To dispatch one ICMP packet to the target host, we would be using 'ping' command with option -c which specifies number of ICMP packets to be sent to the target.

We will then pipe the output of 'ping command' to the 'grep command' that would display the word starting from 'icmp'.

Again, we pipe the output of grep to 'wc command' which when used with option -l counts the number of lines. And this count will be stored in the'$count' variable.

If '$count' is greater than zero, it will denote that we have received an icmp reply from the target host, indicating that the target host is active. And we'll echo 'Yes! Host is Alive!' message on the screen.

On the other hand, if target host doesn't respond, the $count value will be set as zero indicating that the target host is down. In this case, we will display 'Host is not Alive! Try again later..' message on the screen.

Nice little script, but it only works if the ping is not on the same sub-net, For instance as 110 does not exist it still reports the word icmp and returns a 1 to countFrom 192.168.0.110 icmp_seq=1 Destination Host Unreachable