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.

# 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 ];


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


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


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


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:

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...

Posted in   Networking_Tips   Troubleshooting   Scripting   Monitoring   OSSEC   Linux     by trunc_team

Improve Your Websites Speed and Security