Check connectivity to server on any port using code

a small utility to log the connection issue

This blog is about the small utility which help me debug the issue I am in.

Background

I wanted to know if of the server I having continuous connection from my host machine or not, that will help me narrow down the issue with the intermediate connectivity issue I am facing.

Approach

wanted to write the code which will check the connection with source and destination on each minutes so that I can pass the same comment to the network and security team for further investigation.

Implementation

So I started with right way to handle this case using shell first - i found couple of option for this and I chose which fit properly in my case.

Go and create on shell script[name anything, example - connection_test_every_min.sh ] which will have the following content

echo $((echo >/dev/tcp/{your_desire_host}/{port_number}) &>/dev/null && echo "open at: $(date "+%F %H:%M:%S")" || echo "close at: $(date "+%F %H:%M:%S")")

So we wanted to run that every minute, so we can easily use the crontab from the linux, use crontab -e press -> i for enter and paste this

          • /your_script_loc/connection_test_every_min.sh >> /your_script_loc/connection_log.txt 2>&1

Also remember, we also wanted to store the output so we are redirecting that into /your_script_loc/connection_log.txt, where 2> means standard error and &1 means standard output both redirection into the mentioned log file. So what will go and see the stats.

in crontab just store your change using :wq like we do in VI.

bonus - we can also see the cron job log from , where the cron job ran or not and if ran than what time. use the following

tail -f /var/log/cron

Another one where we store the logs, that will look like this

cat connection_log.txt

open at: 2023-01-05 12:40:01

open at: 2023-01-05 12:41:01

open at: 2023-01-05 12:42:01

open at: 2023-01-05 12:43:01

open at: 2023-01-05 12:44:02

open at: 2023-01-05 12:45:01

open at: 2023-01-05 12:46:01

.....

.....

Do let me know if any more information required on this article.