#!/bin/bash ps axu |grep 'nginx' |grep -v 'grep' &>/dev/null if [ $? -ne 0 ] then echo "准备重启nginx...." systemctl restart nginx if [ $? -eq 0 ] then echo "nginx启动成功!" fi else echo "nginx正在运行中...." fi mem_free=`free |awk 'NR==2{print $4}'` mem_total=`free|awk 'NR==2 {print $2}'` mem_left=`echo "scale=2;$mem_free/$mem_total" |bc -l|cut -d. -f2` echo "内存剩余率是:" ${mem_left}% mem_init=90 if [ $mem_left -lt $mem_init ] then msg="TIME:$(date +%F_%T) HOSTNAME:$(hostname) IPADDR:$(ip addr |awk 'NR==9{print $2}') MSG:Memory left lower than the limit,current value is ${mem_left}%" echo "内存剩余不足,会发送邮件" echo $msg /usr/bin/mail $msg fi disk_free=`df |awk 'NR==2{print $4}'` disk_total=`df |awk 'NR==2{print $2}'` disk_left=`echo "scale=2;$disk_free/$disk_total"|bc -l|cut -d. -f2` echo "磁盘剩余率是:" ${disk_left}%
将以上文件保存为serverMonitor.sh 并将该脚本文件的执行添加到定时任务中,使用以下命令打开计划任务编辑页面
crontab -e -u root
在编辑页面,加上一行
* * * * * /usr/bin/sh /root/serverMonitor.sh
保存成功后用 crontab -l 查看计划任务列表
至此,便会每分钟执行一次serverMonitor.sh,查询nginx状态,并监控内存剩余率,发送邮件,
其中,发送邮件的工具代码见
http://www.cnblogs.com/stin/p/7851887.html