Skip to content

Instantly share code, notes, and snippets.

@fwolf
Created August 24, 2011 09:04
Show Gist options
  • Save fwolf/1167646 to your computer and use it in GitHub Desktop.
Save fwolf/1167646 to your computer and use it in GitHub Desktop.
Monitor system mem and load, if too high, restart some service.
#! /bin/bash
#====================================================================
# mt-mon.sh
#
# Copyright (c) 2011, Fwolf <[email protected]>
# All rights reserved.
# Distributed under the GNU General Public License, version 3.0.
#
# Monitor system mem and load, if too high, restart some service.
#
# See: https://wangyan.org/blog/pid-auto-reboot-shell-html.html
#
# V 0.01, since 2011-08-24, hash: .
#====================================================================
if [ $(id -u) != '0' ]; then
echo 'Error: You must be root to run this script!'
exit 1
fi
# Max allowed mem usage
MON_MAX_MEM=85
# Max allowed cpu usage
MON_MAX_CPU=3
# If max exceed, restart thest service
MON_SERVICE='httpd'
function GetStat {
# Mem, total
MEM_TOTAL=`free -k | head -n2 | tail -n1 | awk '{print $2}'`
# Mem, used
MEM_USED=`free -k | head -n2 | tail -n1 | awk '{print $3 - $6 - $7}'`
#echo Used mem: ${MEM_USED}k
# Cpu load
CPU_LOAD=`uptime | awk '{print $(NF-2)}' | sed 's/,//'`
#echo Cpu load: $CPU_LOAD
}
GetStat
#echo Mem: ${MEM_USED}k/${MEM_TOTAL}k, Cpu load: $CPU_LOAD
# Compare
MEM_LIMIT=`echo $MEM_TOTAL \* $MON_MAX_MEM / 100 | bc`
if [[ $MEM_USED > $MEM_LIMIT || $CPU_LOAD > $MON_MAX_CPU ]]; then
echo $(date +'%Y-%m-%d %H:%M:%S') mem or cpu max usage reached,
echo Mem: ${MEM_USED}k/${MEM_TOTAL}k, Cpu load: $CPU_LOAD
echo Restart service: $MON_SERVICE
for SERVICE in $MON_SERVICE; do
/etc/init.d/$SERVICE restart
done
GetStat
echo Mem: ${MEM_USED}k/${MEM_TOTAL}k, Cpu load: $CPU_LOAD
echo
fi
@fwolf
Copy link
Author

fwolf commented Oct 6, 2011

运行的时候输出到日志即可
mt-mon.sh >> /var/log/mt-mon.log

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment