I am trying to create a cron job that would allow me to monitor the status of a particular port and send out notification via email while it changes from listening state to anything else.
-
1What do you use to monitor it? Where are you stuck?– terdonOct 15, 2014 at 11:57
-
I created a shell script to lookup the status of port and then added another line to save that to a file. Further, copy that file across to another server. Below is the script. If I just run the script file it works fine but when the same is added to cron job same content gets repeated twice in every instance. My goal is eventually to create a job that would monitor the status of a port and notify via email when any change occurs.– Vinod BalakrishnanOct 15, 2014 at 12:23
-
PATH=/usr/sbin:${PATH} lsof -i :80 > /root/Desktop/new.txt scp -r /root/Desktop/new.txt [email protected]:/root/desktop/log.txt rm -rf /root/Desktop/new.txt– Vinod BalakrishnanOct 15, 2014 at 12:24
-
1Please edit your question to add extra information, it is hard to read and easy to miss in the comments.– terdonOct 15, 2014 at 12:26
2 Answers
In the simplest case, you could run a command like this:
lsof -i :22 | grep LISTEN
So, to have that run every 5 minutes and send an email if the port is not listening, add this to your crontab:
*/5 * * * * lsof -i :22 | grep LISTEN || echo "Not listening" | mail [email protected]
This, of course, assumes that you have already set up your machine for the mail
command.
The exit code of nc -z localhost port_num
, where port_num
is the port you want to check, might be useful here. If nc
can connect to the port, then the exit code is 0
; otherwise, the exit code is 1
.
You can also add the -v
option to get a printout of the result.