我创建了一个脚本,用于在服务器内存超出阈值限制时发送电子邮件通知。脚本工作正常,但问题是有时我也会收到阈值内存较低的邮件警报。请告诉我原因以及脚本中需要的任何更新?
#!/bin/bash
# Shell script to monitor or watch the high Mem-load
# It will send an email to $ADMIN, if the (memroy load is in %) percentage
# of Mem-load is >= 80%
HOSTNAME=`hostname`
LOAD=80.00
CAT=/bin/cat
MAILFILE=/tmp/mailviews
MAILER=/bin/mail
mailto="[email protected]"
MEM_LOAD=`free -t | awk 'FNR == 2 {printf("Current Memory Utilization is : %.2f%"), $3/$2*100}'`
if [[ $MEM_LOAD > $LOAD ]];
then
PROC=`ps -eo pcpu,pid -o comm= | sort -k1 -n -r | head -1`
echo "Please check your processess on ${HOSTNAME} the value of cpu load is $CPU_LOAD % & $PROC" > $MAILFILE
echo "$(ps axo %mem,pid,euser,cmd | sort -nr | head -n 10)" > $MAILFILE
$CAT $MAILFILE | $MAILER -s "Memory Utilization is High > 80%, $MEM_LOAD % on ${HOSTNAME}" $mailto
fi
答案1
制作这些线:
MEM_LOAD=`free -t | awk 'FNR == 2 {printf("Current Memory Utilization is : %.2f%"), $3/$2*100}'`
if [[ $MEM_LOAD > $LOAD ]];
成为
MEM_LOAD=`free -t | awk 'FNR == 2 {printf("Current Memory Utilization is : %.2f%"), $3/$2*100}'`
MEM_L=`free -t | awk 'FNR == 2 {print int($3/$2*100)}'`
if [ $MEM_L -gt $LOAD ];
您将字符串与数字进行比较。或者你可以跳过一个`awk:
MEM_L=`free -t | awk 'FNR == 2 {print int($3/$2*100)}'`
MEM_LOAD=`echo "Current Memory Utilization is: "${MEM_L} "%"`
if [ $MEM_L -gt $LOAD ];
并使用整数作为 LOAD 变量
LOAD=80
答案2
这是脚本的工作版本,有一些改进:
#!/bin/bash
# Shell script to monitor or watch the high Mem-load
# It will send an email to $ADMIN, if the (memroy load is in %) percentage
# of Mem-load is >= 80%
# you don't need this, $HOSTNAME is a system variable and
## already set.
#HOSTNAME=`hostname`
#Use lowercase variable names to avoid name collision with system variables.
load=80
mailer=/bin/mail
mailto="[email protected]"
## You can't use decimals in a shell arithmetic comparison, but you can use awk
## to do the test for you instead.
if free -t | awk -vm="$load" 'NR == 2 { if($3/$2*100 > m){exit 0}else{exit 1}}'; then
## You weren't setting your "$CPU_LOAD" anywhere. It looks like you want the % use,
## so I am setting it here. Also note how I'm using $() instead of backticks.
## There's nothing wrong with backticks, but the $() is cleaner, easier to nest
## and generally preferred.
cores=$(grep -c processor /proc/cpuinfo)
cpuPerc=$(ps -eo pcpu= | awk -vcores=$cores '{k+=$1}END{printf "%.2f", k/cores}')
## Get the more actual value for reporting
memPerc=$(free -t | awk 'FNR == 2 {printf("%.2f%"), $3/$2*100}')
## Avoid using a temp file
message=$(cat <<EoF
Please check your processess on $HOSTNAME the value of cpu load is $cpuPerc% & Current Memory Utilization is: %$memPerc.
$(ps axo %mem,pid,euser,cmd | sort -nr | head -n 10)
EoF
)
printf '%s\n' "$message" |
"$mailer" -s "Memory Utilization is High > $load%, $memPerc % on $HOSTNAME" \
"$mailto"
fi