一段可用于监测硬盘空间的shell脚本,学习下df命令的详细用法。
在linux中,DF命令可以显示可用的磁盘空间上的文件系统中每个文件名的空间占用数量。
有关df命令的用法,可以参考如下文章:
步骤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:
步骤 3: 编写shell脚本
代码:
#!/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:
# 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) |