Bash Script to Check Apache Memory Usage

We might have come across many situation where we need to find the memory usage by apache and which script or from which directory this process is being called. You can use the script given below to find that and log it whenever the load goes beyond a threshold value. Which also help us to refer later if we want to troubleshoot load issues on the server.

To setup the script follow the simple steps mentioned below.

1. Create a directory /var/log/process_memcheck/

2. Create a file inside /root. I gave the name

3. Grant executable permission to this script.

4. Open the file and paste the following contents in it.

#!/bin/bashVAL=10 #### I gave 10 as threshold value. You can use your own
LOAD=`cat /proc/loadavg | awk -F’ ‘ ‘{print int($1)}’`
IP=`hostname -i`

if [ “$LOAD” -ge “$VAL” ]
for i in $(netstat -plan | grep :80 | grep ESTABLISH | awk ‘{print $7}’ | cut -d/ -f1)
dir=$(lsof -p $i | grep cwd 2> /dev/null| awk ‘{print $9}’);
pid=$(lsof -p $i | grep cwd 2> /dev/null| awk ‘{print $2}’);
memuse=$(pmap -x $pid 2>/dev/null | grep total | sed ‘s/-//g’);
echo “Mem Use = $memuse and home dir = $dir”;
} > /var/log/process_memcheck/process_memcheck-$(date +%d-%m-%y:%H:%M).log

5. Save and quit.

6. Open the file /var/spool/cron/root and append the following line in it.

*/5 * * * * /root/ 

7. Save and quit. Restart crond.

/etc/init.d/crond restart

Thats all. You will get a log at /var/log/process_memcheck/, which show the memory usage by each apache and the directory from which it is being called.

Both comments and pings are currently closed.

Comments are closed.