#! /bin/bash

cpuInfo=

columns=`sar -P ALL 1 1 | grep -v Average | grep -v Linux | grep 0 | grep -v CPU| awk '{print NF}'|sort -u`
if [[ "$columns" == "9" ]];then
   cpuInfo=`sar -P ALL 1 1 | grep -v Average | grep -v Linux | grep 0 | grep all | grep -v CPU| awk '{$1="";$2="";print}'|sort -u`
else
   cpuInfo=`sar -P ALL 1 1 | grep -v Average | grep -v Linux | grep 0 |grep all | grep -v CPU| awk '{$1="";print}'|sort -u`
fi

i=1
parent=

for property in $cpuInfo
do
    t=$(($i%7))
    if [ $t = 0 ];then
        str="$str,'idle':'$property'"
        str="${str#*,}"
        parent="$parent{$str},"
        str=
        i=0
    else
        case $i in 
            1)
                str="$str,'cpname':'cpu'"
                if [[ $property = 'all' ]];then
                    str="$str,'flag':'$property'"
                else
                    str="$str,'flag':'$property'"
                fi
            ;;
            2)
                str="$str,'user':'$property'"
            ;;
            3)
                str="$str,'nice':'$property'"
            ;;
            4)
                str="$str,'system':'$property'"
            ;;
            5)
                str="$str,'iowait':'$property'"
            ;;
            6)
                str="$str,'steal':'$property'"
            ;;

        esac
    fi
    i=$(($i+1))
done

result=`echo ${parent//\'/\"}`
echo "[${result%,*}]"

使用:

[root@sre ~]# bash discover_cpuinfo.sh 
[{"cpname":"cpu","flag":"all","user":"0.50","nice":"0.00","system":"0.00","iowait":"0.00","steal":"0.50","idle":"99.00"}]

发表评论

您的电子邮箱地址不会被公开。

Captcha Code