Simple Remote TCP Port Health Checker for Linux

It’s really easy to write a bash script and create a Simple Remote TCP Port Health Checker on your Linux server. The goal is to check periodically whether a TCP port is open (serving) or not. If the port is not open, we want to log the time and preferably send an email to the system administrator.

The tool has four main parts:

  • TCP connection checker
  • Logger
  • Reporter (optional)
  • Scheduler

In this article we will see how to create a STMP step-by-step.

  • Connection Checker
    1. First you need to have “netcat” tool installed on your Linux machine. For example, in CentOS you can run the following command:
      yum install nc
    2. Then you can use “ncat” command to check the availability of a TCP port. As an example, the below bash script will check whether port number 25 is open on the localhost or not:
      host=localhost port=25 if ! ncat -z $host $port then     echo “Closed!” fi
  • Logger 
    1. Choose a name and path for your log file, create the file and the related directory, then simply cat messages to the log file. Here is one sample:
      echo “Port :”$port” is closed” > /root/logs/ports.log
  •  Reporter
    1. First, mail service should be installed and running on your Linux machine. If the SMTP port (i.e. TCP port number 25) is open on your machine, that’s fine!
    2. Then, you can use the following command in a bash terminal or a bash script:
      mail -s “the email subject”
  • Scheduler
    1. Open “cron” to edit:
      crontab -e
    2. Write a line that suits to your desired monitoring schedule. For example, lets assume that we create a bash script ( with x permission) for monitoring in /root/ directory. Then to schedule it to be run every 3 minutes, we should add the following line to the cron:
      */3 * * * * /root/
      To add this line, after running “crontab -e”, press “i”, then insert this line, press “Esc”, type “:x”, and that’s it.

Sample Bash Script

The following bash script watches four ports and if any of them is not open, creates a log file and sends the log file as an email body:

host=localhost for port in 25 53 80 443 do     if ! ncat -z $host $port     then         date > “/root/logs/log”$port”.log”         echo “——————————-” >> “/root/logs/log”$port”.log”         echo “Port [“$port”] is down” >> “/root/logs/log”$port”.log”         cat “/root/logs/log”$port”.log” | mail -s “Alarm”     fi done

Leave a Reply

Your email address will not be published.