This is a simple useful script which I learned from “Coding For Penetration Testers” book. It is used to check if a host is alive or not and echoes on user screen a message with the results of the ping command, if the host is up it informs the user “HOST IS UP” with the echo command like shown in Figure 1.
We use the if conditional to test if the host is up and print to the screen a message with the echo command, if the host is not alive we print “HOST IS DOWN”, use an else statement to do it. This is the heart of our script, and it is inside a function called pingcheck. As you can see from Figure 1 we declare a function called pingcheck with the function command. After that, we open and close curly brackets and put our code inside it. The ping variable holds the result of the piping process inside backticks. We use ‘ping -c 1′ to ping our target with a single packet and pipe the result of this command with a pipeline to the grep command and grep the word bytes. After that, we use piping again and send the result of grep command to wc command which stands for word cound. The final result of these commands stringed together is stored in the ping variable which we test in the if statement.
The ping variable holds a number, which is the number of word ‘bytes’ returned after ‘ping -c 1 $host’ command is executed. If the value of ping variable is greater than 1 it means that the host has responded to our request, which means the host is alive. The ‘fi’ command inside pingcheck function indicates the end of the if statement. To execute the ping check funtion, we write ‘pingcheck’ outside the function. The first line of this script is the shebang line, which tells the system what interpreter to use in order to interpret the script. The second line is used to get input from the user and $1 means the first argument. To execute this script, open a terminal and type ‘./ping.sh host’, where ping.sh is the Bash script and host is the first argument. For example run ‘./ping.sh www.google.com’ like shown in Figure 2.
The output is shown in Figure 3.