Linux--shell监控CPU和内存

*************************************************************************************************


#! /bin/bash 
#By lzqinfen@126.com




t=`date | awk '{print $4}' |awk -F ':' '{print $1$2$3}'`
d=`date +%m/%d/%Y  |  awk -F '/' '{print $1$2}'`
memfile=/home/walletUser/qhd/$d"-"$t"Mem".txt
cpufile=/home/walletUser/qhd/$d"-"$t"Cpu".txt
max_min_avgfile=/home/walletUser/qhd/$d"-"$t"calculation".txt




#calculate the cpu max
cpu_calc()
{
cpu_max=`cat $cpufile| awk -F ' ' 'BEGIN {max = 0} {if ($6>max) max=$6 fi} END {print "CPU_Max=", max}'`
cpu_min=`cat $cpufile|awk -F ' ' 'BEGIN {min = 1000} {if ($6<min) min=$6 fi} END {print "CPU_Min=", min}'`
cpu_avg=`cat $cpufile| awk -F ' '  '{sum+=$6} END {print "CPU_Average = ", sum/NR}'`
echo   $cpu_max" "$cpu_min" "$cpu_avg"%"
}


#calculate the mem max
mem_calc()
{
mem_max=`cat $memfile| awk -F ' ' 'BEGIN {max = 0} {if ($6>max) max=$6 fi} END {print "MEM_Max=", max}'`
mem_min=`cat $memfile|awk -F ' ' 'BEGIN {min = 999000} {if ($6<min) min=$6 fi} END {print "MEM_Min=", min}'`
mem_avg=`cat $memfile| awk -F ' '  '{sum+=$6} END {print "MEM_Average = ", sum/NR}'`
echo   $mem_max" "$mem_min" "$mem_avg"%"
}




# watch memory usage 
watch_mem()
{
dd1=`date | awk '{print $2,$3,$4}'`


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)) 
mem_message=$dd1" Memory usage: $mem_usage%" 
echo $mem_message >>$memfile


trap "echo '**********The results are as follows***********';echo `cpu_calc`|tee >>$max_min_avgfile;echo `mem_calc`|tee >>$max_min_avgfile;cat $max_min_avgfile;echo '*****************`date`*************';exit" 2
sleep 10s
}


# watch cpu 
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 5s 
time_point_2=`get_cpu_info`
dd2=`date | awk '{print $2,$3,$4}'` 
cpu_usage=`echo $time_point_1 $time_point_2|awk '{used=$3-$1;total=$3+$4-$1-$2;print used*100/total}'` 
cpu_message=$dd2" CPU Usage: $cpu_usage%" 
echo $cpu_message >>$cpufile





while :
do
#trap "echo `cpu_max`;exit" 2
watch_cpu
watch_mem
#trap "echo `cpu_max`;exit" 2
done
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值