常用shell(3):shell监控nginx所有进程cpu,内存占用

1. 脚本

注: 仅centos测试通过,ubuntu测试失败

# !/bin/bash
# author:liaotuo
if [ -e cpu_mr.log ]
then
    rm -f cpu_mr.log
fi

pid_array=(122)

#get all pid by proName
funGetPids(){
    ps -C nginx -o pid > pids.txt
    sed -i '1d' pids.txt #delete the first line
    i=0;
    while read line   
    do
        pid_array[$i]=$line
        echo ${pid_array[$i]}
        let "i++"
    done < pids.txt
    # echo $pid_array
    return
}
funGetPids

interval=1
while true
do
    sum_vmrss=0
    sum_cpu=0
    for pid in  ${pid_array[@]}
    do
        vmrss_temp=`cat /proc/$pid/status|grep -e VmRSS|tr -cd "[0-9]"`
        # echo $vmrss_temp
        sum_vmrss=`expr $sum_vmrss + $vmrss_temp`
        cpu=`top -n 1 -p $pid|tail -2|head -1|awk '{ssd=NF-4} {print $ssd}'`
        # echo $cpu
        # sum_cpu=`expr $sum_cpu + $cpu`
        sum_cpu=$(echo "$sum_cpu+$cpu"|bc)
    done
    # echo "-------------------"
    echo "sum_vmrss: " $sum_vmrss >> cpu_mr.log
    echo "sum_cpu: " $sum_cpu >> cpu_mr.log
    # echo "-------------------"
    echo "complete"
    sleep $interval
done

2. 使用

$ sh monitor.sh

注: 如果遇到Syntax error: “(” unexpected 错误,以 $ bash monitor.sh 运行

3. 日志

  • 日志保存在 cpu_mr.log文件中
    常用shell(3):shell监控nginx所有进程cpu,内存占用_第1张图片

  • sum_vmrss :nginx 内存总占用

  • sum_cpu:cpu总占用

你可能感兴趣的:(shell)