Bash 监控磁盘使用情况

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5648158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:47:10  来源:igfitidea点击:

Bash monitor disk usage

linuxbashshelldebiandisk

提问by RailsSon

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

我买了一个 NAS 盒子,里面有一个精简版的 debian。

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.

前几天它用完了空间,我没有意识到。我基本上想编写一个 bash 脚本,当磁盘空间超过 90% 时它会提醒我。

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

有没有人知道一个脚本可以做到这一点,或者给我一些关于编写脚本的建议?

回答by Erik

#!/bin/bash
source /etc/profile

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

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

Crontab this to run however often you want an alert

Crontab 这个可以运行,但你经常需要一个警报

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",*100 / ); }'`
  if [ $p -ge 90 ]
  then
    df -h $devname | mail -s "$devname is low on space" [email protected]
  fi
done

回答by HaveAGuess

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 dfitself.

我尝试使用 Erik 的答案,但在设备名称过长的情况下遇到问题,这些设备名称包含数字并导致脚本失败,而且数学对我来说看起来是错误的,并且与df自身报告的百分比不符。

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", ) }'`
  if [ $p -ge 70 ]
  then
    df -h $devname | mail -s "$devname is low on space" [email protected]
  fi
done

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

主要变化是改变df -kdf -Pk以避免换行,并简化了awk来,计算值:前使用百分比,而不是recalcing。

回答by Jonatan Littke

You could also use Monitfor 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".

您也可以将Monit用于此类工作。它是“用于在 UNIX 系统上管理和监视进程、程序、文件、目录和文件系统的免费开源实用程序”。