当前位置: > shell编程 >

监测硬盘空间的shell脚本

时间:2014-12-05 02:15来源:www.it.net.cn 作者:IT
一段可用于监测硬盘空间的shell脚本,学习下df命令的详细用法。

在linux中,DF命令可以显示可用的磁盘空间上的文件系统中每个文件名的空间占用数量。
如果没有指定文件名,显示所有当前挂载的文件系统的可用空间。

有关df命令的用法,可以参考如下文章:
du与df在统计linux文件占用空间上的区别
Linux磁盘管理命令df和du

脚本编写步骤分为三步,如下所示。

步骤1:取得磁盘空间:
 

 
$ df -H
Output:
Filesystem             Size   Used  Avail Use% Mounted on
/dev/hdb1               20G    14G   5.5G  71% /
tmpfs                  394M   4.1k   394M   1% /dev/shm
/dev/hdb5               29G    27G   654M  98% /nas/www

步骤 2:过滤掉头部信息,取得空间占用百分比
 

 

$ df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }'

Output:
71% /dev/hdb1
98% /dev/hdb5

步骤 3: 编写shell脚本
以上命令中显示df命令的字段5和1。
现在,写一个脚本来查看空间的百分比是否> =90%。

代码:
 

#!/bin/sh
df -H | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{ print $5 " " $1 }' | while read output;
do
  echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1  )
  partition=$(echo $output | awk '{ print $2 }' )
  if [ $usep -ge 90 ]; then
    echo "Running out of space \"$partition ($usep%)\" on $(hostname) as on $(date)" |
     mail -s "Alert: Almost out of disk space $usep%" you@somewhere.com
  fi
done

设置计划任务crontab:
首先,将脚本复制到 /etc/cron.daily/ 目录中。
 

 
# cp diskAlert /etc/cron.daily/
# chmod +x /etc/cron.daily/diskAlert

创建计划任务:
 

crontab -e
10 0 * * * /path/to/diskAlert

完整脚本代码:
 

#!/bin/sh
# set -x
# 监测与显示硬盘空间情况
# 当硬盘空间使用率 >= 90%,则发邮件告知系统管理员。
# Edit www.it.net.cn IT网 IT网.COM
# -------------------------------------------------------------------------

ADMIN="root"
# set alert level 90% is default
ALERT=90
# Exclude list of unwanted monitoring, if several partions then use "|" to separate the partitions.
# An example: EXCLUDE_LIST="/dev/hdd1|/dev/hdc5"
EXCLUDE_LIST="/auto/ripper"
#
#::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
function main_prog() {
while read output;
do
#echo $output
  usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1)
  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
}
if [ "$EXCLUDE_LIST" != "" ] ; then
  df -H | grep -vE "^Filesystem|tmpfs|cdrom|${EXCLUDE_LIST}" | awk '{print $5 " " $6}' | main_prog
else
  df -H | grep -vE "^Filesystem|tmpfs|cdrom" | awk '{print $5 " " $6}' | main_prog
fi




(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容