監控cpu與memory指令碼

germany006發表於2014-06-11
#!/bin/bash
#################Begin of input_declare#################
#Get Cpu Value
CPU_get=$(/usr/bin/sar -u 1 1 | awk 'NR==4{print $8}')
cpu_idle=$(echo ${CPU_get})
CpuUsedCal=$(echo "scale=2;100-${cpu_idle}"|bc)
#Get Memory Value
MemTotal_get=$(cat /proc/meminfo | awk 'NR==1{print $2}')
MemFree_get=$(cat /proc/meminfo | awk 'NR==2{print $2}')
Buffers_get=$(cat /proc/meminfo | awk 'NR==3{print $2}')
Cached_get=$(cat /proc/meminfo | awk 'NR==4{print $2}')
MemTotal=$(echo ${MemTotal_get})
MemFree=$(echo ${MemFree_get})
Buffers=$(echo ${Buffers_get})
Cached=$(echo ${Cached_get})
MEM_cal=$(echo "scale=2;100*(${MemTotal}-${MemFree}-${Buffers}-${Cached})/${MemTotal}"|bc)
MemUsedPerc=$(echo ${MEM_cal})
#Set Time Format
v_time=$(date "+%F %T")
v_mon=$(date +%Y%m)
v_del_mon=$(date -d "12 months ago" +%Y%m)
#Set Path
v_cpu_path=/data/log/cpu_used_perc_logs/
v_mem_path=/data/log/mem_used_perc_logs/
#################End of input_declare###################
#################Begin of main#################
if [ -d ${v_cpu_path} ];then 
echo  "${v_time}"       >>  ${v_cpu_path}cpu_used_perc${v_mon}.log
echo  "${CpuUsedCal}%"  >>  ${v_cpu_path}cpu_used_perc${v_mon}.log
else
mkdir -p ${v_cpu_path}
fi
if [ -f ${v_cpu_path}cpu_used_perc${v_del_mon}.log ];then
rm -f ${v_cpu_path}cpu_used_perc${v_del_mon}.log
fi


if [ -d ${v_mem_path} ];then 
echo  "${v_time}"       >>  ${v_mem_path}mem_used_perc${v_mon}.log
echo "${MemUsedPerc}%"  >>  ${v_mem_path}mem_used_perc${v_mon}.log
else
mkdir -p ${v_mem_path}
fi
if [ -f ${v_mem_path}mem_used_perc${v_del_mon}.log ];then
rm -f ${v_mem_path}mem_used_perc${v_del_mon}.log
fi
#################end of main###################

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28371090/viewspace-1180479/,如需轉載,請註明出處,否則將追究法律責任。

相關文章