Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Sunday, 17 November 2013

A Simple BASH Script To Ping Remote Host and Check if a Specific Port is Open



    It's time to write a script and this time we will create a script that pings a remote host and checks whether a certain port is opened or not. The result is mailed to user's email ID and displayed on the screen at the same time.

Steps

  • Create a variable 'Host' to store the details of the host to be pinged (Name or it's IP address).
  • Create another variable 'Port' to store the port number to be checked.
  • Create variables 'email_id' and 'email_sub' to store email ID of the user and the subject of the email respectively.
  • When script is executed, it will expect the user to enter two arguments, Host and Port Number. If the user does not enter these entities, flash an error message on the screen.
  • Ping the 'Host' and store the result in a variable called 'result_host'.
  • Use nc command to check whether the 'Port' is opened or not. Store the result in a variable 'result_port'.
  • Combine there two results to create a message 'mesg' which will be dispatched to 'email_id' using mail command and displayed on the terminal screen.
Note: To install a package for mail command, run following command:

sudo apt-get install mailutils

Script


#!/bin/bash

if [ "$#" = "0" ];
then
    echo Error:
    echo "Usage: $0 [Host] [Port Number]"
    exit 1
fi

Host=$1
Port=$2
email_id="username@domain.com"
email_sub="Result"

if ping -q -c 5 $Host >/dev/null
then
    result_host="Successful"
else
    result_host="Not Successful"
fi

result_nc='nc -z $Host $Port; echo $?'

if [ $result_nc != 0 ];
then
    result_port="Not Opened"
else
    result_port="Opened"
fi

mesg="Ping to host was ${result_ping}, Port $port is ${result_port}."

echo "$mesg"

echo "$mesg" | mail -s "$email_sub" $email_id


0 comments:

Post a Comment