Linux系统中需要监控磁盘各分区的使用情 况,避免由于各种突发情况,造成磁盘空间被消耗殆尽的情况,例如某个分区被Oracle的归档日志耗尽,导致后续的日志文件无法归档,这时ORACLE数 据库就会出现错误。监控磁盘空间的使用情况,其实有许多工具,例如Nagios等,其实最简单的还是使用Shell脚本。下面就介绍一下如何通过 Shell脚本和Crontab作业结合来实现对磁盘空间的监控、告警。
一般查看磁盘各分区的使用情况可以通过df命令来查看,网上有两种获取磁盘使用百分比的Shell脚本。
1:df -h | grep /dev | awk '{print $5}' | cut -f 1 -d "%"
2:df -h | grep /dev | awk '{print $5}' | sed 's/%//g'
但是这两个命令还是有些bug,例如如下截图所示:当显示内容过长,导致换行时。此时上面的Shell脚本就无法获取其值。
尤其是某些特殊情况下,完全无法准确获取相应数据
此时只需在参数上稍微做一下调整即可
1:df -P | grep /dev | awk '{print $5}' | cut -f 1 -d "%"
2:df -P | grep /dev | awk '{print $5}' | sed 's/%//g'
下面脚本是用来监控各分区使用情况,当超过阀值(默认为90%)时,发出告警邮件,通知管理员及时处理。
#*************************************************************************
# FileName : disk_capatiy_alarm.sh
#*************************************************************************
# Author : Kerry
# CreateDate : 2013-11-07
# Description : this script is mointoring the linux disk
# capacity, if disk used more than 90%,
# then it will send a alarm email
#*************************************************************************
#! /bin/bash
email_content="/home/oracle/scripts/output/disk_sendmail.pl"
email_logfile="/home/oracle/scripts/output/diskdetail.txt";
cat /dev/null > ${email_content};
cat /dev/null > ${email_logfile};
SendMail()
{
date_today=`date +%Y_%m_%d`
subject="The server xxxxxx\'s Disk Capacity Alarm"
content="Dear All,
The server xxxx(xxx.xxx.xxx.xxx) disk capacity alarm ,please take action for it. many thanks!
"
echo "#!/usr/bin/perl" >> ${email_content}
echo "use Mail::Sender;" >> ${email_content}
echo "\$sender = new Mail::Sender {smtp => 'xxx.xxx.xxx.xxx', from => 'xxx@xxx.com'}; ">> ${email_content}
echo "\$sender->MailFile({to => 'kerry@xxx.com',">> ${email_content}
echo "cc=>'xxxx@xxxx.com'," >> ${email_content}
echo "subject => '$subject',">> ${email_content}
echo "msg => '$content',">> ${email_content}
echo "file => '${email_logfile}'});">> ${email_content}
perl ${email_content}
}
for d in `df -P | grep /dev | awk '{print $5}' | sed 's/%//g'`
do
if [ $d -gt 90 ]; then
df -h >>$email_logfile;
SendMail;
exit 0;
fi
done