有关于通过bash脚本发送关于光盘空间的邮件的问题。
每隔30,59分钟crontab启动bash脚本,如果磁盘空间达到90%则发送电子邮件。现在2个文件系统达到90%,每个crontab开始我收到相同问题的相同电子邮件。如何更新脚本以不向我发送相同的电子邮件,但是,如果光盘空间在90-100%限制内发生变化?
谢谢
df -h | grep -v '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
echo $output
partition=$(echo $output | awk '{print $2}')
if [ $usep -ge $ALERT ] ; then
echo "Running out of space \"$partition ($usep%)\" on server $(hostname), $(date)" | \
mail -s "Alert: Almost out of disk space $usep%" $ADMIN
fi
done
答案 0 :(得分:0)
怎么样:
report=$(
df -hP | awk -v alert="$ALERT" -v h="$(hostname)" -v d="$(date)" '
(!/^Filesystem|tmpfs|cdrom/) && $5 > alert {
printf "Running out of space \"%s %d\" on server %s, %s\n", $1, $5, h, d
}
'
)
if [[ "$report" ]]; then
mail -s "Alert: Almost out of disk space $usep%" "$ADMIN" <<<"$report"
fi
我将所有逻辑推入awk,并在发送一封电子邮件之前收集了所有结果。
如果的使用率超过90%,则不会阻止电子邮件。为此,您必须将当前结果写入文件,并在下一次迭代时读取文件并检查更改。
答案 1 :(得分:0)
将先前使用空间的百分比存储在文件中,将其读入数组,并在最后写入新的百分比。
#!/bin/bash
## File with partitions and percent full
last_usep=/path/file
## If the file exists, read lines into array
if [[ -f $last_usep ]] ; then
## Associative array
declare -A map_usep
while read line ; do
partition=$(echo $line | awk '{print $1}')
usep=$(echo $line | awk '{print $2}')
map_usep[$partition]=$usep
done < $last_usep
fi
## Check partitions
df -h | \
grep -v '^Filesystem|tmpfs|cdrom' | \
awk '{ print $5 " " $1 }' | \
while read output; do
usep=$(echo $output | awk '{print $1}')
partition=$(echo $output | awk '{print $2}')
## If "usep" has not changed, skip to next iteration. Otherwise, store the new percentage
if [[ $usep== ${map_usep[$partition]} ]] ; then
continue
else
map_usep[$partition]=$usep
fi
if [ $usep -ge $ALERT ] ; then
echo "Running out of space \"$partition ($usep%)\" on server $(hostname), $(date)" | \
mail -s "Alert: Almost out of disk space $usep%" $ADMIN
fi
done
## Update the file with new percentages
\rm $last_usep
touch $last_usep
for partition in "${!usep[@]}" ; do
echo $partition ${usep[$partition]} >> $last_usep
done