CPU 사용량 스크립트와 같이 메모리 부하가 일어났을 때,
어떤 프로세스가 메모리 사용이 많았는지 메일 발송이 되는 스크립트입니다.

#!/bin/bash
s_time=$(date +%Y-%m-%d' '%H:%M:%S)

while true; do

#memory usage
TOTAL=`free | awk '/^Mem:/    { printf( "%s\n", $2 ); }'`
USED=`free | awk '/^Mem:/    { printf( "%s\n", $3 ); }'`
FREE=`free | awk '/^Mem:/    { printf( "%s\n", $4 ); }'`
BUFFERS=`free | awk '/^Mem:/    { printf( "%s\n", $6 ); }'`
CACHED=`free | awk '/^Mem:/    { printf( "%s\n", $7 ); }'`

#cat /proc/meminfo | egrep 'MemTotal|MemFree|Buffers|Cached' | grep -v 'SwapCached' | awk '{print $2}' > $TMP_DIR/memory.$$

usage=$(expr $FREE + $BUFFERS + $CACHED)
used=`expr $TOTAL - $FREE - $BUFFERS - $CACHED`
#mem_usage=`echo "$used / $TOTAL * 100"|bc -l`
#mem_usage=$(echo "scale=2; $used/$TOTAL*100"|bc -l)
let "mem_usage=$used*100/$TOTAL"

if [ "$mem_usage" -ge 90 ]; then
 Process=`/bin/ps -eo pmem,pcpu,rss,vsize,args | /bin/sort -k 1 -r | /usr/bin/head -n 20`
 echo -e "$(hostname) as on $s_time \n $Process\n" | mail -s "Alert: Almost out of memory space $mem_usage%" root@test.com
fi

  # Wait before checking again.
  sleep 300

done

Posted by 박물지