서버 메모리가 임계값 한도를 초과하면 이메일 알림을 보내는 스크립트를 만들었습니다. 스크립트는 잘 작동하지만 문제는 가끔 메모리 임계값이 낮은 메일 알림도 받는다는 것입니다. 스크립트에 필요한 이유와 업데이트가 있는지 알려주십시오.
#!/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