LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Bash script to check if process is running and send email (http://www.linuxquestions.org/questions/linux-newbie-8/bash-script-to-check-if-process-is-running-and-send-email-717595/)

depam 04-07-2009 11:28 PM

Bash script to check if process is running and send email
 
Hi,

Can you please help on giving me a script that will check certain process (httpd, xmail) every hour and send email if it is not running?

I already have a tool to send an email automatically but I need a bash script to include in crontab to run every hour.

Thanks.

laitcg 04-08-2009 12:04 AM

#!/bin/bash
if ! `pidof program` ;then
mail -s "program bit the dust" root@localhost
fi

replacing program with your programs cli name

anotherlinuxuser 04-08-2009 12:11 AM

Here's a simple shell you can use:

Scripts starts on next line:
#!/bin/bash

ps -ef | grep -v grep | grep "some command in the process list" \
> dev/null
if [ $? -ne 0 ]; then
'put your email command here.'
fi

# End of Script

The 'ps -ef' will list all processes on the system.
The '| grep -v grep' will filter out our 'ps' process to prevent a false
positive.

The '| grep "some command in the process list"' will find, or will not find, the process you are checking.
When selecting a string to look for, keep in mind you have to look for something unique to the program you want find. A generic search for "mail" will match 'sendmail', 'qmail', etc. so try to include some white space, like: ' xmail '. Don't include dates or process numbers, as they will change.

The '\' just means continue the same command on the next line.
We redirect any output to '> /dev/null' so we don't get a email from cron every time the script runs.

The 'if [ $? -ne 0 ]; then' checks if the second grep found what we were looking for. Since we are only concerned when the process is not found, we check for a not equal to 0 return from the grep command.

Replace the 'put your email command here.' with your own email command.
Remember that cron only sets a basic environment, so if your email program is not in one the standard program dirs,
"/usr/local/bin:/usr/bin:/bin", you must use a complete path to the program, ie.: /usr/mydir/bin/myemailprog {options}
You can put more than 1 command inside the if ... fi statement.
Good luck.


All times are GMT -5. The time now is 04:08 PM.