老李分享:shell 监控cpu,memory,load average 2

# 获取内存使用情况

function GetMem() {

    mem=$(free -m | sed -n '3,3p')

    used=$(echo $mem | awk -F ' ' '{print $3}')

    free=$(echo $mem | awk -F ' ' '{print $4}')

    total=$(($used + $free))

    limit=$(($total/10))

    echo "${total} ${used} ${free}"

 

    local remark

    remark=$(GetRemark ${MEM_REMARK})

 

    # 检查内存占用是否超过90%

    if [ "$remark" = "" ] && [ "$limit" -gt "$free" ]; then

        echo "Subject: ${HOST} Memory uses more than 90% $(date +%Y-%m-%d' '%H:%M:%S)" | sendmail ${NOTICE_EMAIL}

        echo "$(date +%s)" > "$MEM_REMARK"

    fi

}

 

# 获取load average

function GetLoad() {

    load=$(uptime | awk -F 'load average: ' '{print $2}')

    m1=$(echo $load | awk -F ', ' '{print $1}')

    m5=$(echo $load | awk -F ', ' '{print $2}')

    m15=$(echo $load | awk -F ', ' '{print $3}')

    echo "${m1} ${m5} ${m15}"

 

    m1u=$(echo $m1 | awk -F '.' '{print $1}')

 

    local remark

    remark=$(GetRemark ${LOAD_REMARK})

 

    # 检查是否负载是否有压力

    if [ "$remark" = "" ] && [ "$m1u" -gt "2" ]; then

        echo "Subject: ${HOST} Load Average more than 2 $(date +%Y-%m-%d' '%H:%M:%S)" | sendmail ${NOTICE_EMAIL}

        echo "$(date +%s)" > "$LOAD_REMARK"

    fi

}

 

# 获取上一次发送电邮时间

function GetRemark() {

    local remark

 

    if [ -f "$1" ] && [ -s "$1" ]; then

        remark=$(cat $1)

 

        if [ $(( $NOW - $remark )) -gt "$REMARK_EXPIRE" ]; then

            rm -f $1

            remark=""

        fi

    else

        remark=""

    fi

 

    echo $remark

}

 

 

# *** function end ***

 

cpuinfo=$(GetCpu)

meminfo=$(GetMem)

loadinfo=$(GetLoad)

 

echo "cpu: ${cpuinfo}" >> "${CPU_LOG}"

echo "mem: ${meminfo}" >> "${MEM_LOG}"

echo "load: ${loadinfo}" >> "${LOAD_LOG}"

 

exit 0

 

crontab

* * * * * /home/xxxx/ServerMonitor.sh
* * * * * sleep 30; /home/xxxx/ServerMonitor.sh

 


你可能感兴趣的:(软件测试开发)