email_alerts_on_low_free_space
This is an old revision of the document!
Email alerts on low free space
Create /root/free-space-alerts.pl
:
#!/usr/bin/perl # Based on: # http://www.cyberciti.biz/tips/howto-write-perl-script-to-monitor-disk-space.html use strict; use warnings; use Filesys::DiskSpace; if (@ARGV != 3) { die "Syntax: $0 <email_address> <path> <min_space_GB>\n"; } my ($to,$dir,$warning_level) = @ARGV; my $hostname = `hostname` || 'localhost'; chomp $hostname; # email setup my $subject = "$hostname: Low disk space on $dir"; # get df my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir; $used /= 1024*1024; # to GB $avail /= 1024*1024; # to GB my $total = $used + $avail; my $pct = $avail/$total*100; # compare if ($avail < $warning_level) { open MAIL, "| /usr/bin/mail $to -s '$subject'" or die "mail: $!\n"; printf MAIL "WARNING from '$hostname'.\n\nLow disk space on $dir: %.1fGB / %.1fGB free (%.1f%%)\n",$avail,$total,$pct; close MAIL; }
Then create /etc/cron.hourly/free-space-alerts
with one line per mountpoint to monitor:
/root/free-space-alerts.pl <YOUR_EMAIL_ADDRESS> <DIRECTORY> <MINIMUM_SPACE_IN_GIGABYTES> ...
Alternate version that doesn't use Filesys::DiskSpace
If you don't have that module, use this:
#!/usr/bin/perl # Based on: # http://www.cyberciti.biz/tips/howto-write-perl-script-to-monitor-disk-space.html use strict; use warnings; #use Filesys::DiskSpace; if (@ARGV != 3) { die "Syntax: $0 <email_address> <path> <min_space_GB>\n"; } my ($to,$dir,$warning_level) = @ARGV; my $hostname = `hostname` || 'localhost'; chomp $hostname; # email setup my $subject = "$hostname: Low disk space on $dir"; # get df my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = my_df($dir); $used /= 1024*1024; # to GB $avail /= 1024*1024; # to GB my $total = $used + $avail; my $pct = $avail/$total*100; # compare if ($avail < $warning_level) { open MAIL, "| mail $to -s '$subject'" or die "mail: $!\n"; printf MAIL "WARNING from '$hostname'.\n\nLow disk space on $dir: %.1fGB / %.1fGB free (%.1f%%)\n",$avail,$total,$pct; close MAIL; } sub my_df { my ($p) = @_; #Filesystem 1024-blocks Used Available Capacity Mounted on open DF, "df -P $p |" or die "df: $!\n"; scalar <DF>; # eat header my $line = <DF>; close DF; my ($dev,$total,$used,$avail,$pct,$mountpoint) = split(/\s+/,$line); return (0, '', $used, $avail, 0, 0); # (mostly) compatible with Filesys::DiskSpace }
email_alerts_on_low_free_space.1250616246.txt.gz · Last modified: 2009/08/18 10:24 (external edit)