Friday, May 2, 2008

Automatically Restart Dead Services Via Bash Scripting

#!/bin/bash

# Services Restarter - Automatically restart httpd if they die

/bin/netstat -ln | /bin/grep ":80 " | /usr/bin/wc -l |

/bin/awk '{if ($1 == 0) system("/sbin/service httpd restart") }'


/bin/netstat -ln

Invokes the netstat command to list all listening ports and using presenting bound IP addresses in numeric format. The reason we’d want to use the numeric format for IPs is that it is much faster because we’re not resolving the IPs to hostnames.

| /bin/grep ":80 "

We then pipe the output of netstat to grep looking for addresses that are listening to port 80.

If you noticed, we actually checked for ":80 "; ie 80 with a space afterwards. The reason for the space is to filter out other services that run on ports 8000 or 8080 for example, which will be matched if we were to just use :80.

| /usr/bin/wc -l

Next, we pipe the output of grep to wc, which is essentially a command line word counter.

The -l flag used simply tells wc to count the total number of objects passed to it. Since we already grep-ed the relevant ports, this would return either 0 if the service has died or 1 if it’s alive and listening.

| /bin/awk '{if ($1 == 0) system("/sbin/service httpd restart") }'

Following that, we pass the output sent out by wc to awk, a fast text processing engine that can be programmed to do perform simple text processing jobs.

Here, we simply want awk to tell us if the argument passed to it was 0 (the number zero). If this is the case, then run /sbin/service httpd restart (the command to start the httpd service).

Add this script in crontab >
*/1 * * * *


No comments: