Shell Script to Automate apache service restart

Apache HTTP Server

Usually when we get error in Apache error.log files we need to restart. To do so we need to monitor the error.log file constantly which is tiring. We do the monitoring using crontab and below script. Make sure you modify according to your requirement before putting it in contab which will check the error.log file each 5minutes. Incase it finds errors more than the set number of times  in error.log it will send out  a mail to the admins, stored in email.txt file before restarting the apache service.

Below script checks if the last hour has more than 150 errors, If it finds it “Yes” then the script will restart the Apache service automatically, after sending an email to Admin to avoid Apache Crashes. We will be including the apache service restart command in this script to automate the same.

The single line of command will also rotate the error.log file while restarting.

 #!/bin/sh
/bin/source ~/.bash_profile

#Mention the ID/User used to start the apache service
ApacheID=root

#Setting the date format to that which is found in the log
DATE=`/bin/date +\%b" "\%d" "\%H`

#Statement to check if the last hour has more than 150 errors registered in error.log file of Apache

if [ `/bin/grep "$DATE" /opt/apache/logs/error.log | /bin/awk '{print $2" "$3" "$4}' | /bin/awk 'BEGIN {FS=":"};{print $1":"$2}' | /usr/bin/uniq -c | /bin/awk '{print " "$1" "}' | /bin/grep -v " 1 " | /bin/awk '{tot=tot+$1} END {print tot+1}'` -gt 150 ]

then

#Setting up the email message file
email="/tmp/email.txt"

#Sending the output of top for user webadm to the email message body
/usr/bin/top -b -U $ApacheID -n 1 >$email

#Appending a line break to the email body
echo "">>$email

#This command sends the current semaphore count to the email body
/usr/bin/ipcs -s>>$email

#Send the composed email message
/bin/mail -s "Some problem found in Error log file; Restarting Apache Service" "[email protected]" < $email

#Stopping Apache
/opt/apache/bin/apachectl stop

#This makes sure that Apache stops/sleeps before continuing
while [ `ps -eaf | grep [h]ttpd | wc -l` -gt 0 ]
do
sleep 1
done

#Clean up any memory available, If memhog utility is not available in your system then comment out below line qith a # mark
/usr/bin/memhog 1G

#Rotate the error log file to a fresh one keeping a backup of old.
mv /opt/apache/logs/error.log /opt/apache/logs/error.log_restarted_`date +\%Y.\%m.\%d.\%H`

#Start-up Apache
/opt/apache/bin/apachectl start

fi

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.