bash 使用 SAR 命令查找 CPU 使用率的 Shell 脚本,如果使用率超过 75%,则发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15203158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:44:13  来源:igfitidea点击:

Shell script to find cpu utilization using SAR command and send email if usage is more than 75 percent

bashshellunix

提问by mishra1010

13:30:01          CPU     %user     %nice   %system   %iowait    %steal     %idle
13:40:01          all      0.56      1.21      0.69      1.64      0.00     95.89
Average:          all      0.63      1.25     11.10      7.48      0.00     79.55

Here is the output of sar command. I want to add the %user and %system from the average and if its more than 75 percent send an email to user. please help and also please let me know if there is any better method to calculate cpu usage.

这是 sar 命令的输出。我想从平均值中添加 %user 和 %system,如果超过 75%,则向用户发送电子邮件。请帮忙,也请让我知道是否有更好的方法来计算 CPU 使用率。

回答by Istvan Koncz

#!/bin/bash
saveIFS=$IFS
IFS=$' '
USAGE=( $( sar | tail -1 | cut -c20-29,40-49 ) )
IFS=$saveIFS
SUM=0
for (( CNTR=0; CNTR<${#USAGE[@]}; CNTR+=1 )); do
    FLOAT=( $( echo ${USAGE[$CNTR]} | tr ',' '.' ) )
    SUM=( $( echo "$SUM+$FLOAT" |bc  ) )
done
INT=${SUM/.*}
echo $INT
if [[ $INT == "" ]]; then
    INT=0
fi
if [ $INT -ge 75 ]; then
    mail -s "CPU usage is above 75%" [email protected] < $INT
fi

回答by David

#!/bin/bash
TMPFILE=/tmp/CPUtmp
sar |awk ' == "Average:"{T=+; if (T > 75){print T}}' > $TMPFILE
if [ -s $TMPFILE ] ; then
  mail -s "CPU usage is above 75%" [email protected] < $TMPFILE
fi

If you want current utilization, "sar 5 6" instead of "sar" will check at 5-second intervals for half a minute.

如果您想要当前的利用率,“sar 5 6”而不是“sar”将以 5 秒的间隔检查半分钟。