Bash monitor disk usage

ⅰ亾dé卋堺 提交于 2019-12-21 10:31:50

问题


I bought a NAS box which has a cut down version of debian on it.

It ran out of space the other day and I did not realise. I am basically wanting to write a bash script that will alert me whenever the disk gets over 90% full.

Is anyone aware of a script that will do this or give me some advice on writing one?


回答1:


#!/bin/bash
source /etc/profile

# Device to check
devname="/dev/sdb1"

let p=`df -k $devname | grep -v ^File | awk '{printf ("%i",$3*100 / $2); }'`
if [ $p -ge 90 ]
then
  df -h $devname | mail -s "Low on space" my@email.com
fi

Crontab this to run however often you want an alert

EDIT: For multiple disks

#!/bin/bash
source /etc/profile

# Devices to check
devnames="/dev/sdb1 /dev/sda1"

for devname in $devnames
do
  let p=`df -k $devname | grep -v ^File | awk '{printf ("%i",$3*100 / $2); }'`
  if [ $p -ge 90 ]
  then
    df -h $devname | mail -s "$devname is low on space" my@email.com
  fi
done



回答2:


I tried to use Erik's answer but had issues with devices having long names which wraps the numbers and causes script to fail, also the math looked wrong to me and didn't match the percentages reported by df itself.

Here's an update to his script:

#!/bin/bash
source /etc/profile

# Devices to check
devnames="/dev/sda1 /dev/md1 /dev/mapper/vg1-mysqldisk1 /dev/mapper/vg4-ctsshare1 /dev/mapper/vg2-jbossdisk1 /dev/mapper/vg5-ctsarchive1 /dev/mapper/vg3-muledisk1"


for devname in $devnames
do
  let p=`df -Pk $devname | grep -v ^File | awk '{printf ("%i", $5) }'`
  if [ $p -ge 70 ]
  then
    df -h $devname | mail -s "$devname is low on space" my@email.com
  fi
done

Key changes are changed df -k to df -Pk to avoid line wrapping and simplified the awk to use pre-calc'd percent instead of recalcing.




回答3:


You could also use Monit for this kind of job. It's a "free open source utility for managing and monitoring, processes, programs, files, directories and filesystems on a UNIX system".



来源:https://stackoverflow.com/questions/5648158/bash-monitor-disk-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!