Thursday, 7 March 2013

Perl script to monitor disk space and send an email

There is a nice perl system routine called Perl df or Filesys::DiskSpace. This routine displays information on a file system such as its type, the amount of disk space occupied, the total disk space and the number of inodes etc.

Task: Install Filesys::DiskSpace

First you need to install this perl module using apt-get or from cpan (Comprehensive Perl Archive Network).

Command : sudo apt-get install libfilesys-diskspace-perl

Perl script code to monitor disk space and send an email alert.

#!/usr/bin/perl
# Available under BSD License.
use strict;
use warnings;
use Filesys::DiskSpace;

# file system to monitor
my $dir = "/home";

# warning level
my $warning_level=10;

# email setup
my $to='admin@yourdomain.com';
my $from='webmaster@YOURDOMAIN.COM';
my $subject='Low Disk Space';

# get df
my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir;

# calculate 
my $df_free = (($avail) / ($avail+$used)) * 100.0;

# compare 
if ($df_free < $warning_level) {
my $out = sprintf("WARNING Low Disk Space on $dir : %0.2f%% ()\n",$df_free);

# send email using UNIX/Linux sendmail
open(MAIL, "|/usr/sbin/sendmail -t");

## Mail Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n";

## Mail Body
print MAIL $out;

close(MAIL);
}
 

No comments:

Post a Comment