统计cpu脚本

统计cpu信息,写文件

#!/bin/bash
LANG=en_US.UTF-8
cpuUsed=` top  -n 1| awk  -F  '[, %]+'  'NR==3 {print 100-$11}' `
diskUsed=$( df  -h| awk  -F  '[ %]+'   '/\/$/{print $5}' )
logFile= /tmp/jiankong .log
  
function  Sendmail(){
     mail -s "监控报警"  user@oldboyedu.com <$logFile
}
  
function  check(){
     if  [ ` echo "$cpuUsed>80" | bc ` - eq  1 -o $diskUsed - ge  85 ]; then
        echo "CPU使用率:${cpuUsed}%,磁盘使用率:${diskUsed}%" >$logFile
       Sendmail
     fi
}
  
function  main(){
     check
}
 
main

 

#! /bin/sh
# 查询占用CPU的进程
dateString=$(date +"%Y-%m-%d_%H:%M:%S")
resultFile="result_track-cpu_${dateString}.txt"
processCount=3
echo "结果文件: $resultFile" 

heads[1]='User(用户)'
heads[2]='PID(进程)'
heads[3]='%CPU(占用CPU)'
heads[4]='%MEM(占用内存)'
heads[8]='STAT(状态)'
heads[11]='COMMAND(命令)'

getLinePart() {
    local line=$1
    local serialNumber=$2
    if [ $serialNumber -eq 11 ]
    then 
        echo $line | awk '{for (i=11;i<=NF;i++) prin $i;}' | xargs
    else
        echo $line | awk "{print \$$[$serialNumber]}"
    fi
}

ps -aux | sort -k3nr | head -n $processCount | while read line
do
    cpuPart=`getLinePart "$line" 3`
    if [ $cpuPart == '0.0' ]
    then
        break
    fi
    processSerialNumber = $((processSerialNumber + 1))
    echo "进程: $processSerialNumber" >> $resultFile

    echo "${line}">>$resultFile
    
    for headSerialNumber in ${!heads[@]}
    do
        title=${heads[$headSerialNumber]}
        part=`getLinePart "$line" $headSerialNumber`
        echo "${title}: $part" >> $resultFile
    done
    echo "" >> $resultFile
done
echo "结果文件: $resultFile" 

 

posted @ 2020-10-20 00:00  楠鸽  阅读(129)  评论(0编辑  收藏  举报