monitor wordpress site through bash script

Have created a small bash script to monitor wordpress site status and report to the web admin in near real time. I really enjoyed the benefit of outcome of this script. What it does?

Script will monitor the apache access log constantly. Identifies the suspicious activity or error scenario and email to web admin. At the same time identified suspicious log entries are collected in different log file for easier analysis.

The logs been read and processed immediately once they arrived. Since we benefit receiving alert mail in near real time. This make us to take action immediately.

Step1

Do login as root or user who has access to read apache logs.

#mkdir $HOME/web_status && cd $HOME/web_status

#touch fw_script.sh

###<<copy below content to fwscript.sh file>>###

!#/bin/bash
LOGFILE=”/opt/apache2/logs/access_log”
wc -l $HOME/web_status/errors_detected |awk '{print $1}' > $HOME/web_status/PLC.tmp
tail -Fn0 $LOGFILE |
while read line
do
echo $line |awk '($9>=300 && $9!=304 || $7 ~ /xmlrpc.php/ ){print}' >> $HOME/web_status/errors_detected
done

Note: Replace your apache access log file path at LOGFILE variable definition.

Step 2

#touch mail_error.sh

###<< copy the below content to mail_error.sh file. Replace firewall@example.com and sysadmin@example.com with your appropriate mail id’s >>###

LC=`wc -l $HOME/web_status/errors_detected |awk '{print $1}'`
PLC=`cat $HOME/web_status/PLC.tmp`
ERR=`expr $PLC + 5`

if [ "$LC" -gt "$ERR" ]; then
DT=`date +%d%b%y-%H:%m`
tail -n5 $HOME/web_status/errors_detected| mailx –r firewall@example.com -s "Errors identified - $DT" sysadmin@example.com
wc -l $HOME/web_status/errors_detected |awk '{print $1}' > $HOME/web_status/PLC.tmp
fi

if [ "`ps -ef |grep fw_script.sh|grep -v grep |wc -l`" -lt "1" ]; then
sh $HOME/web_status/fw_script.sh &
echo "started fw_script.sh by `date`"
fi

Step3

Place the below entry in user cron tab.

#crontab –e
* * * * * /bin/sh $HOME/web_status/mail_error.sh >> $HOME/web_status/log

The filter pattern used to to short error/suspicious can be changed as per your requirement. In above script below conditions are checked,

  1. Is the request is  to access xmlrpc.php?
  2. Any failure HTTP request but ignore cache request (status code 304)

Was the information useful? Any modification required? Leave your comments below.