*************************************************************************************************
#! /bin/bash
#By [email protected]
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
Linux--shell监控CPU和内存,布布扣,bubuko.com