サーバーメモリがしきい値制限を超えると、電子メール通知を送信するスクリプトを作成しました。スクリプトはうまく機能しますが、問題は時々メモリしきい値の低いメール通知も受け取ることです。スクリプトに必要な理由とアップデートがあるかどうか教えてください。
#!/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