在linux下监控cpu、内存、磁盘数据等信息,用shell脚本是最合适不过的了。
以下脚本用来测试CPU压力,接收一个参数为:CPU数量。
例如:
# ./killcpu.sh 2 
产生两个进程号,记住这2个进程号,测试完后杀掉进程,释放CPU资源。
代码如下:
 
调用示例,如下图:
 
 
以下是今天要介绍的主要脚本,监测服务器CPU、内存MEM、磁盘DISK数据。
代码如下:
 
#!/bin/bash 
#filename seerver_moniter.sh
mem_quota=20 
hd_quota=50 
cpu_quota=80
 
# watch memory usage 
 
watch_mem() 
{ 
  memtotal=`cat /proc/meminfo |grep "MemTotal"|awk '{print $2}'` 
  memfree=`cat /proc/meminfo |grep "MemFree"|awk '{print $2}'` 
  cached=`cat /proc/meminfo |grep "^Cached"|awk '{print $2}'` 
  buffers=`cat /proc/meminfo |grep "Buffers"|awk '{print $2}'` 
 
  mem_usage=$((100-memfree*100/memtotal-buffers*100/memtotal-cached*100/memtotal)) 
 
  if [ $mem_usage -gt $mem_quota ];then 
    mem_message="WARN! The Memory usage is over than $mem_usage%" 
    return 1 
    else 
    return 0 
  fi 
}
# watch disk usage 
 
watch_hd() 
{ 
  sda1_usage=`df |grep 'sda1'|awk '{print $5}'|sed 's/%//g'` 
  sda2_usage=`df |grep 'sda2'|awk '{print $5}'|sed 's/%//g'` 
  lv01_usage=`df |grep opt|awk '{print $4}'|sed 's/%//g'` 
  
  if [ $sda1_usage -gt $hd_quota ] || [ $sda2_usage -gt $hd_quota ] || [ $lv01_usage -gt $hd_quota ]; then 
    hd_message="WARN! The Hard Disk usage is over than $hd_quota%" 
    return 1 
    else 
    return 0 
  fi 
}
# watch cpu usage in one minute 
get_cpu_info() 
{ 
  cat /proc/stat|grep '^cpu[0-9]'|awk '{used+=$2+$3+$4;unused+=$5+$6+$7+$8} END{print used,unused}' 
} 
 
watch_cpu() 
{ 
  time_point_1=`get_cpu_info` 
  sleep 60 
  time_point_2=`get_cpu_info` 
  cpu_usage=`echo $time_point_1 $time_point_2|awk '{used=$3-$1;total=$3+$4-$1-$2;print used*100/total}'` 
  
  if [[ $cpu_usage > $cpu_quota ]]; then 
    cpu_message="WARN! The CPU Usage is over than $cpu_quota%" 
    return 1 
    else 
    return 0 
  fi 
} 
 
proc_cpu_top10() 
{ 
  proc_busiest=`ps aux|sort -nk3r|head -n 11` 
}
report=/root/server_report.log 
watch_mem 
if [ $? -eq 1 ]; then 
  date >> $report 
  echo "$mem_message" >> $report 
fi 
 
watch_hd 
if [ $? -eq 1 ]; then 
  date >> $report 
  echo "$hd_message" >> $report 
fi 
 
watch_cpu 
if [ $? -eq 1 ]; then 
  date >> $report 
  echo "$cpu_message" >> $report 
  proc_cpu_top10 
  echo "$proc_busiest" >> $report 
fi 
 
if [ -a $report ]; then 
  mail -s "CUP/MEM/DISK Stat of Alarm" monitor@jb200.com < $report  
  rm -rf $report #为看到测试结果,可注释此行
fi
脚本说明:
 
加入定时任务:
 
每10分钟调用一次本脚本。
调用示例,如下图:
 
 
总结:
此监控脚本不错,特别是加入定时任务以后,实时监控系统的CPU、内存、磁盘空间、排在前10的CPU资源占用情况。
收藏它吧,会有用的。
您可能感兴趣的文章:
监测服务器内存、磁盘、cpu、swap的脚本
几个shell自动化脚本(定期清理、磁盘空间、搜寻关键字)
shell磁盘监控及报警的脚本
提取磁盘IO与系统负载Load的shell脚本
监视远程磁盘的健康情况的shell脚本
磁盘空间使用状况检测脚本
linux 查看磁盘IO状态的方法
监控磁盘空间使用率的脚本