#!/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
togrep
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
towc
, which is essentially a command line word counter.The
-l
flag used simply tellswc
to count the total number of objects passed to it. Since we alreadygrep
-ed the relevant ports, this would return either 0 if the service has died or 1 if it’s alive and listening.
Add this script in crontab >
| /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).
*/1 * * * *
No comments:
Post a Comment