1. Home
  2. Tips and Tricks
  3. Monitor the Status of a Service with a Bash Script

Monitor the Status of a Service with a Bash Script

When you manage multiple servers it’s sometimes impossible to stay ahead of the various administrative tasks, which is why automation is so important.

If you’re working on a linux based server and want to monitor the status of a service, here is a quick an easy way to automate that process.

#!/bin/bash
# Script to find if a service is running

for i in ossec-monitord ossec-logcollector ossec-integratord;

 do ps auwx | grep -v grep | grep $i >/dev/null 2>&1 ;

   if [ $? = 0 ];

    then

     echo `date "+%Y-%m-%d %H:%M "`"$i Running...";

    else

     echo `date "+%Y-%m-%d %H:%M "`"$i not running...";

fi;

What we did above is create a simple loop looking for three distinct services:

ossec-monitord
ossec-logcollector
ossec-integratord

Those three services are assigned to the i variable, and that variable is then passed into the grep query here:

ps auwx | grep -v grep | grep $i >/dev/null 2>&1 ;

What we’re also doing above is cutting out any grep inquiries, because if you were to run a grep command it will show as a process as shown here in red:

root@server:~/scripts# ps auwx | grep ossec-logcollector

root      1260  0.0  0.0   4876  1784 ?        S    May19   0:03 /var/ossec/bin/ossec-logcollector
root     29353  0.0  0.0  14428  1116 pts/0    S+   20:59   0:00 grep --color=auto ossec-logcollector

By cutting out the grep request you see this response:

root@server:~/scripts# ps auwx | grep -v grep | grep ossec-logcollector

root      1260  0.0  0.0   4876  1784 ?        S    May19   0:03 /var/ossec/bin/ossec-logcollector

This is important because this if [ $? = 0 ]; is looking for the grep exit value of 0, which states:

EXIT STATUS
The grep utility exits with one of the following values:
0     One or more lines were selected.
1     No lines were selected.
>1    An error occurred.

With this selection, if you run the grep and there are no service running it would still find the grep service itself. It’d give you a false positive response.

echo `date "+%Y-%m-%d %H:%M "`"$i Running...";

It passes each argument through the loop. If the service is found to be running it prints:

2020-05-19 18:27 ossec-monitord Running...
2020-05-19 18:27 ossec-logcollector Running...
2020-05-19 18:27 ossec-integratord Running...
Updated on December 8, 2023
Was this article helpful?

Related Articles

Need Support?
Can’t find the answer you’re looking for? Don’t worry we’re here to help!
Email: support@noc.org

Leave a Comment