1.獲取cpu相關資訊
#cpu個數
cpuCount=`cat /proc/cpuinfo| grep "physical id"| sort| uniq| wc -l`
#cpu核數
cpuNucleus=`cat /proc/cpuinfo| grep "cpu cores"| uniq | awk -F ':' '{print $2}'`
#cpu總核數
cpuTotalNucleus=$(echo "$cpuCount*$cpuNucleus"|bc)
#cpu執行緒數
cpuThreadCount=`cat /proc/cpuinfo| grep "processor"| wc -l`
#cpu型號
modelName=`grep 'model name' /proc/cpuinfo | sed -n '$p' | awk -F ':' '{print $2}'`
#cpu使用率
#CPU時間計算公式:CPU_TIME=user+system+nice+idle+iowait+irq+softirq
#CPU使用率計算公式:cpu_usage=(idle2-idle1)/(cpu2-cpu1)*100
#預設時間間隔
TIME_INTERVAL=5
time=$(date "+%Y-%m-%d %H:%M:%S")
LAST_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
LAST_SYS_IDLE=$(echo $LAST_CPU_INFO | awk '{print $4}')
LAST_TOTAL_CPU_T=$(echo $LAST_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
sleep ${TIME_INTERVAL}
NEXT_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
NEXT_SYS_IDLE=$(echo $NEXT_CPU_INFO | awk '{print $4}')
NEXT_TOTAL_CPU_T=$(echo $NEXT_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
#系統空閒時間
SYSTEM_IDLE=`echo ${NEXT_SYS_IDLE} ${LAST_SYS_IDLE} | awk '{print $1-$2}'`
#CPU總時間
TOTAL_TIME=`echo ${NEXT_TOTAL_CPU_T} ${LAST_TOTAL_CPU_T} | awk '{print $1-$2}'`
#CPU使用率
CPU_USAGE=`echo ${SYSTEM_IDLE} ${TOTAL_TIME} | awk '{printf "%.2f", 100-$1/$2*100}'`
2.記憶體相關資訊統計
#總記憶體大小
mem_total=`free -m | sed -n '2p' |awk '{print $2}'`
#已使用記憶體
mem_used=`free -m | sed -n '2p' |awk '{print $3}'`
#剩餘記憶體
mem_free=`free -m |sed -n '2p' |awk '{print $4}'`
#使用記憶體百分比
Percent_mem_used=`echo "scale=2; $mem_used / $mem_total *100" | bc`
#剩餘記憶體百分比
Percent_mem_free=`echo "scale=2; $mem_free / $mem_total *100" | bc`