Perl script to monitor disk space and send an email

Posted on in Categories Debian Linux, File system, FreeBSD, Gentoo Linux, Howto, Linux, Monitoring, OpenBSD, OS X, Perl, RedHat/Fedora Linux, Sys admin, Tips, Ubuntu Linux, UNIX last updated February 21, 2007

Here is a quick question by one of our regular reader :

How to write a perl script that can monitor my disk space under UNIX or Linux and send me an email alert?

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).
$ sudo apt-get install libfilesys-diskspace-perl

Perl script code to monitor disk space

Now write a perl script called df.pl:
$ vi df.pl
Append following code:

#!/usr/bin/perl
use strict;
use warnings;
use Filesys::DiskSpace;
 
# file system /home or /dev/sda5
my $dir = "/home";
 
# get data for /home fs
my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir;
 
# calculate free space in %
my $df_free = (($avail) / ($avail+$used)) * 100.0;
 
# display message
my $out = sprintf("Disk space on $dir == %0.2f\n",$df_free);
print $out;

Save and close the file. Run this script as follows:
$ chmod +x df.pl
$ ./df.pl

Output:

Disk space on /home == 75.35

So /home has 75.35% free disk space. Next logical step is to compare this number to limit so that you can send an email if only 10% free disk space is left on /home file system. Here is the code with

#!/usr/bin/perl
use strict;
use warnings;
use Filesys::DiskSpace;
 
my $dir = "/home";
 
# warning level 10%
my $warning_level=10;
 
my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = df $dir;
my $df_free = (($avail) / ($avail+$used)) * 100.0;
 
# compare free disk space with warning level
if ($df_free < $warning_level) {
my $out = sprintf("Send an Email - Disk space on $dir => %0.2f%% (WARNING Low Disk Space)\n",$df_free);
print $out;
}
else
{
my $out = sprintf("Disk space on $dir => %0.2f%% (OK)\n",$df_free);
print $out;
}

Run script as follows:
$ ./df.pl
Output:

Send an Email - Disk space on /home => 3.99% (WARNING Low Disk Space)

Here is final code that send an email alert ( download):

#!/usr/bin/perl
# Available under BSD License. See url for more info:
# http://www.cyberciti.biz/tips/howto-write-perl-script-to-monitor-disk-space.html
use strict;
use warnings;
use Filesys::DiskSpace;
 
# file system to monitor
my $dir = "/home";
 
# warning level
my $warning_level=10;
 
# email setup
my $to='[email protected]';
my $from='[email protected]';
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);
}

You can run this script as a cron job:
@hourly /path/to/df.pl

Recommended readings

=> Read man page of this module by typing following command:
$ man filesys::diskspace

=> CPAN filesys::diskspace webpage

=> Sending mail with Perl mail script and How do I send html email from Perl?

=> Shell script to monitor or watch the disk space

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

36 comment

  1. Nice script.

    I though had to change the sendmail part to:

    ## Mail Header
    print MAIL “To: $ton”;
    print MAIL “From: $fromn”;
    print MAIL “Subject: $subjectn”;

    to get sendmail working correctly.

  2. IMHO, it would be better to implement a server monitoring system, which will also allow monitoring of other metrics, such as CPU utilisation, memory use, network port counts, log messages, network traffic, network checks, and more.

    I use hobbit for this, which supports all of this out-the-box, and with no configuration required to have the memory, cpu utilisation, disk usage graphs working.

  3. Although your perl script is nice, you could do it with a standard shell script as well:

    for fs in `df -k|awk '{print $1}'|sed -n "2,14 p"`; do
       x="`df -kl | grep $fs | awk '{ print $5 }'| sed -e 's/%//'`"
       y="75"
       if [ $fs != "kernfs" ]; then
         if [ $fs != "procfs" ]; then
           if [ "${x}" -gt "${y}" ]; then
             message="File System `df -k |grep $fs |a
    wk '{print $6","$5}'` Full"
             echo $message | mail -s "`hostname` - Fi
    le System Full Warning" root
           fi
         fi
       fi
    done
  4. @Markus / Buchan

    I do agree with all of you monit is much better but one of our loyal and regular reader wanted perl script.

    @Pete
    Thanks for a shell script.

    Appreciate all of your posts.

  5. I am installing the Filesys::diskspace module and when I do make test I get the error as
    ———————————————-
    t/linux-ext2…..Can’t use an undefined variable as ARRAY reference at t/linux-ext2.t line26
    ——————————————–

    Anyone has encountered this problem previously..can you please tell me what the problem is

  6. I get this error

    “Cannot use df on this machine (untested or unsupported). ”

    everything installed (moudles etc..)

    can some one help me?

    thank you!

  7. How we can make tests that we don’t send multiple e-mails? I’ve done that in shell scripts by setting up /tmp/mail_sent file and checking if it exists. After I logged onto a machine and free up some disk, I would remove the lock file.
    My Perl is a bit rusty, so can anyone write the enhancement?

  8. Well, for multiple e-mails, here it is:

    ## Mail Body
    if (-e "/tmp/sms_sent")
    {
    print "already sent";
    }
    else
    {
    print MAIL $out;
    system ("touch /tmp/sms_sent");
    }

  9. Hi!

    I tried running the script on my mac os x leopard 10.5.3 machine and it says “Cannot use df on this machine (untested or unsupported).”

    What should I do? Sorry I’m quite a newbie into this thing.

  10. For RPM based Linux systems like CentOS and Fedora, install the perl-Filesys-DiskSpace package with:
    # yum install perl-Filesys-DiskSpace

  11. Hi

    I am a newbie to perl programming. Can somebody explain the following line? I understood rest of the program except for this bit. How are we getting this array out of the df command?

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

    Thanks for your help!

    1. Hi RC,
      I have just basic knowledge of UNIX Cmd and now want to write Unix PErl Script.
      .which book I can refer to go with.

      Thanks,

  12. the df command there is part of the perl library FileSys::DiskSpace and not the normal df command available from the OS. This script is short and sweet but in my opinion, overly dependant on external libraries. The whole thing could have been written thusly..

    #!/usr/bin/perl
    use strict;
    use warnings;
     
    # file system to monitor
    my $target = shift;
     
    # warning level
    my $warning_level=10;
     
    # email setup
    my $to='[email protected]';
    my $from='[email protected]';
    my $subject='Low Disk Space Warning';
     
    # get df
    my ($fs_dev, $fs_type, $size, $used, $avail, $use, $mount) = split(" ", `df -PT $target | tail +2`);
     
    # calculate
    my $df_free = (($avail) / ($avail+$used)) * 100.0;
     
    # compare
    if ($df_free &lt; $warning_level) {
    my $out = sprintf("WARNING Low Disk Space on $target : %0.2f%% ()n",$df_free);
     
    # send email using UNIX/Linux sendmail
    open(MAIL, "|/usr/sbin/sendmail -t");
     
    ## Mail Header
    print MAIL "To: $ton";
    print MAIL "From: $fromn";
    print MAIL "Subject: $subjectn";
     
    ## Mail Body
    print MAIL $out;
     
    close(MAIL);
    }
  13. Guys, my script is slightly different, basically i’m wanna count files in a directory and after certain amount of files, the script should send me alert.

    I’ve two problems with the current.

    1. I’m recieving emails but without body message
    2. I’m getting following error while execute this script:

    Useless use of private variable in void context at ./VMCount.pl line 38.

    However there is nothing wrong with line# 38, as i hve “}” on this line

    any comments?

  14. Hello,
    would enyone tell me why do I get such an error during execution of Kens script:
    —————————————–
    Use of uninitialized value in concatenation (.) or string at ./new_df.pl line 17.
    tail: cannot open `+2′ for reading: No such file or directory
    Use of uninitialized value in addition (+) at ./new_df.pl line 20.
    Use of uninitialized value in addition (+) at ./new_df.pl line 20.
    Use of uninitialized value in division (/) at ./new_df.pl line 20.
    Illegal division by zero at ./new_df.pl line 20.
    ——————————————
    It happens also during execution of original script from article above:
    ——————————————
    Illegal division by zero at ./df.pl line 26.
    ——————————————
    both errors are about the same line:
    my $df_free = (($avail) / ($avail+$used)) * 100.0;
    I have perl-Filesys-DiskSpace installed in my system.
    I do not understand what it is complaining about
    Any ideas?

  15. Dear Peter,

    > Although your perl script is nice, you could do it with a standard shell script as well:

    for fs in `df -k|awk ‘{print $1}’|sed -n “2,14 p”`; do
    x=”`df -kl | grep $fs | awk ‘{ print $5 }’| sed -e ‘s/%//’`”

    done

    Why do You use pipe snakes, like df -k|awk ‘{print $1}’|sed -n “2,14 p” and df -kl | grep $fs | awk ‘{ print $5 }’| sed -e ‘s/%//’??? If You start awk why do You need a grep and sed? On the other hand if You have n disks You call df (n+1) times instead of once.

    Good byte!

  16. HI
    I am newnie in perl programming..
    I am getting this error “An error occured. statvfs failed. Did you run h2ph?”
    Could anyone help what is this error mean? and how to solve it?

    Thanks

  17. Hi ,

    I am a newbie in perl….can any body tell how to use the same script when i am using windows -XP?

    Thanks in advance

  18. sorry I’m new in hardware programing.
    can I use vb6 / .net programing to monitor disk space and send an email under Linux ?

  19. Hi All,
    I am very new to Unix. Just got a new assignment where I need to write Unix Perl Script.
    Can some one segues me which book can help to know Perl script for beginner.
    Please help..with link also.

    Thanks

  20. Cant get this script to run. Can anyone help?

    running on Solaris 10

    Makefile.PL and make complete successfully
    make test spits out errors

    # make test
    PERL_DL_NONLAZY=1 /usr/bin/perl “-MExtUtils::Command::MM” “-e” “test_harness(0, ‘blib/lib’, ‘blib/arch’)” t/*.t
    t/1st…………ok
    t/freebsd-ufs….skipped
    all skipped: no reason given
    t/linux-ext2…..skipped
    all skipped: no reason given
    t/linux-vfat…..skipped
    all skipped: no reason given
    t/solaris-ufs….An error occured. statvfs failed. Did you run h2ph?
    FAILED before any test output arrived
    Failed Test Stat Wstat Total Fail Failed List of Failed
    —————————————————————–
    t/solaris-ufs.t ?? ?? % ??
    3 tests skipped.
    Failed 1/5 test scripts, 80.00% okay. 8/9 subtests failed, 11.11% okay.
    *** Error code 29
    make: Fatal error: Command failed for target `test_dynamic’

    running h2ph hangs after ‘redefine’ message
    # h2ph -r -l
    require ‘_h2ph_pre.ph’;
    no warnings ‘redefine’; // hangs here

    I added require ‘_h2ph_pre.ph’; to the h2ph and re-ran with the same result.

    What’s up with this?
    Solaris 10

  21. Thanks for the script. I tweaked it so that it would monitor multiple folders. I also added a “–test” command line option to send out a test email. Here it is:

    #!/usr/bin/perl
    # Available under BSD License. See url for more info:
    # http://www.cyberciti.biz/tips/howto-write-perl-script-to-monitor-disk-space.html
    # Pass in command line parameter "--test" to perform an email test.
    use strict;
    use warnings;
    use Filesys::DiskSpace;
    
    
    # ---------------------------
    # Configuration section
    # ---------------------------
    
    # default warning level
    my $default_warning_level=10;
    
    # email setup
    my $to='[email protected]';
    my $from='[email protected]';
    my $subject='Low Disk Space';
    
    # folders to check
    sub perform_checks {
        &check_free_space("/", 30);
        &check_free_space("/mnt/data");
        &check_free_space("/mnt/storage");
        &check_free_space("/mnt/backup", 20);
    }
    
    
    # ---------------------------
    # Main script
    # ---------------------------
    
    my $out = "";
    
    # Check free space for folder and add to email message if it is below warning level.
    # Parameters:
    #   folder_to_check - The path of the filesystem to check.
    #   warning_level - If the free disk space percentage is below this level,
    #                   an email is sent.  If this parameter is omitted, the
    #                   default level will be used.
    sub check_free_space {
        my ($dir, $warning_level) = @_;
    
        # set warning level to default if not specified
        if(!defined($warning_level)) {
            $warning_level = $default_warning_level;
        }
    
        # 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) || (defined($ARGV[0]) && ($ARGV[0] eq "--test"))) {
            # append to email
            $out .= sprintf("WARNING Low Disk Space on $dir : %0.2f%% ()n",$df_free);
        }
    }
    
    &perform_checks;
    
    # check if there are warnings to email
    if($out ne "") {
        # send email using UNIX/Linux sendmail
        open(MAIL, "|/usr/sbin/sendmail -t");
    
        ## Mail Header
        print MAIL "To: $ton";
        print MAIL "From: $fromn";
        print MAIL "Subject: $subjectn";
    
        ## Mail Body
        print MAIL $out;
    }
    
    close(MAIL);
  22. I am getting this issue on 64-bit RHEL and CentOS:

    Illegal division by zero at ./df.pl line 23.

    Line 23 is
    my $df_free = (($avail) / ($avail+$used)) * 100.0;

    1. Try this works for me:
      my ($fs_type, $fs_desc, $used, $avail, $fused, $favail) = split(” “, `df -PT $dir | tail -n +2`);

  23. i want to concatenate $_ and $var in to $new in perl ,but it is not concatenating why?
    $new = “$_”.”/$var”;
    @arr1= `ls -a $new`;

  24. Any Tutorials for perl scripting.. I would need a perl script to find cpu utilization on a solaris host.

    Thanks Arun

  25. This checks all volumes on the system, and sends out a warning vs critical notice.

    #!/usr/bin/perl -w
    
    # check_disk_space.pl
    # Send an email notice out when mounted file systems are past a given percentage.
    #
    # Perl v5.8.8
    # Tested under RHEL4, RHEL5, and RHEL6
    #
    # When this script is run it will check the status of all mounted file systems
    # using the df command and if the percentage is past the given critical set level
    # will send out an email notice every time it is run. A set warning percentage
    # only send out an email every number_of_days_before_next_warning.
    # It keeps track of the number_of_days_before_next_warning using lock files.
    #
    # The check_disk_space.xml config file should be in the same directory as the program,
    # and be given the same name if the program name is changed.
    #
    #check_disk_space.xml
    # < =
    #-
    #
    #  90
    #  99
    #  7
    #  /home//
    #  yes
    #  no
    #  /bin/df
    #  /bin/find
    #  /bin/rm
    #  /bin/date
    #  /bin/hostname
    #  /usr/sbin/sendmail
    #  [email protected]
    #  Disk Check <[email protected]>
    #  Disk Check
    #
    #  Disk Check
    #
    #-
    #
    #  The following config toggles whether the host appears in the subject line.
    #  A value of "yes" will trigger the hostname include.
    #  no
    #
    # The following line troggles weather or not lock files are created with a
    # hidden dot prefix. A value of "yes" will trigger the hidden file.
    # yes
    #
    # The following line determins where the lock files will be placed. If left
    # blank the lock files will be saved in the current directory. Be sure to
    # end a directory path with a "/" in the config file.
    #/home//
    #
    # This program doesn't require any special privlege accesses, except read/write
    # access to the lockfile directory.
    #
    # Recommended Crontab Entry:
    # # Check precentage of disk used every day and send out a email if critical levels are reached.
    # 0 7 * * * cd /home//bin; /home//bin/check_disk_space.pl
    #
    # Script requirements: install XML Simple
    # yum install perl-XML-Simple
    #
    # History:
    # ---------------------------------------------------------------------------
    # 2014-02-24  kienenbe    Started, works.
    #
    
    use XML::Simple;
    use File::Basename;
    #use Data::Dumper;
    
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Get the mount points from the df command.
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    sub get_filesystem_data {
      my @mount_points;
      my $df_line;
      my $filesystem;
      my $junk;
      my $total_size;
      my $amount_used;
      my $amount_avalible;
      my $percent_used;
    
      my @df_output = `$command_df -lh`;
    
      foreach $df_line (@df_output) {
        if ($df_line =~ m#d%#) {
          #print "->$df_line";
    
          # Break out the needed data.
          ($percent_used,$filesystem) = split(/% /, $df_line);
          chomp $filesystem;
          ($junk,$total_size,$amount_used,$amount_avalible,$percent_used) = split(/s+/, $percent_used);
    
          # Record the data for the filesystem mount point.
          $filesystem_info{"$filesystem"}{"total_size"} = "$total_size";
          $filesystem_info{"$filesystem"}{"amount_used"} = "$amount_used";
          $filesystem_info{"$filesystem"}{"amount_avalible"} = "$amount_avalible";
          $filesystem_info{"$filesystem"}{"percent_used"} = "$percent_used";
        }
      }
    }
    
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Format the text report output for display.
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    #       system.mysystem.org
    #       Fri Feb 21 13:47:03 UTC 2014
    #
    #  ---- Critical file system space at or above 45% ----
    #
    #       Size  Used Avail  Use% Mounted on
    #       1.8T  769G  973G   45% /mnt/backup
    #       1.1T  436G  550G   45% /data
    #
    #  ---- Warning file system space at or above 8% ----
    #
    #       Size  Used Avail  Use% Mounted on
    #       485M   38M  422M    9% /boot
    
    sub format_report_output {
      $warning_duplicate_check  = 0;
      $critical_duplicate_check = 0;
      my $filename;
    
    
      # Cycle though each filesystem mount point.
      foreach my $filesystem (keys %filesystem_info) {
    
        if ($filesystem_info{"$filesystem"}{"percent_used"} >= $critical_percent_used) {
    
          if ($critical_duplicate_check eq 0) {
    
              # Only print the date and time stamp if this is the first warning check.
              if ($warning_duplicate_check eq 0) {
                $formated_report .= "n      $Hostnamen      $TimeStampn";
              }
            $formated_report .= "n ---- Critical file system space at or above ${critical_percent_used}% ----nn";
            $formated_report .= sprintf("     %5s %5s %5s %5s %-60sn", "Size","Used","Avail","Use%","Mounted on");
            $critical_duplicate_check = 1;
          }
          $formated_report .= sprintf("     %5s %5s %5s %5s %-60sn", $filesystem_info{$filesystem}{total_size},$filesystem_info{$filesystem}{amount_used},$filesystem_info{$filesystem}{amount_avalible},"$filesystem_info{$filesystem}{percent_used}%",$filesystem);
        }
    
        elsif ($filesystem_info{"$filesystem"}{"percent_used"} >= $warning_percent_used) {
    
          # Concert the file system mount point to a file name.
          $filename = &convert_filesystem_path_to_name($filesystem);
    
          # Remove warning locks for file system mount points past the number_of_days_before_next_warning
          &remove_warning_lockfile($filename);
    
          if (&check_for_warning_lockfile($filename)) {
            # Do nothing
          }
          else {
    
            if ($warning_duplicate_check eq 0) {
    
              # Only print the date and time stamp if this is the first critical check.
              if ($critical_duplicate_check eq 0) {
                $formated_report .= "n      $Hostnamen      $TimeStampn";
              }
              $formated_report .= "n ---- Warning file system space at or above ${warning_percent_used}% ----nn";
              $formated_report .= sprintf("     %5s %5s %5s %5s %-60sn", "Size","Used","Avail","Use%","Mounted on");
              $warning_duplicate_check = 1;
            }
            $formated_report .= sprintf("     %5s %5s %5s %5s %-60sn", $filesystem_info{$filesystem}{total_size},$filesystem_info{$filesystem}{amount_used},$filesystem_info{$filesystem}{amount_avalible},"$filesystem_info{$filesystem}{percent_used}%",$filesystem);
    
            # Create a warning lock file for the current file system mount point.
            &write_warning_lockfile($filename);
          }
        }
      }
    }
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Send out the email to the recipients.
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    sub send_email_notice {
    
      # Send full report to recepiants(s)
    
      # Remove complaint about global empty vars such as ${mail_subject_postfix}
      no warnings 'uninitialized';
    
      if (  $warning_duplicate_check eq 1 or $critical_duplicate_check eq 1) {
        open (MAIL, "|$command_sendmail -t") || die "Can't open the mail binary: ${command_sendmail}!n";
        print MAIL "X-Mailer: ${mail_x_mailer}n";
        print MAIL "Return-Path: [email protected]${Hostname}n";
        print MAIL "From: ${mail_from} n";
        print MAIL "To: ${mail_to}n";
        if ($Include_Hostname_In_Subject eq "yes") {
          print MAIL "Subject: ${mail_subject_prefix}${Hostname}${mail_subject_postfix}nn";
        }
        else {
          print MAIL "Subject: ${mail_subject_prefix}${mail_subject_postfix}nn";
        }
        print MAIL "n${formated_report}nn";
        close (MAIL);
      }
    }
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Conver the file system mount point to a lockfile name.
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    sub convert_filesystem_path_to_name {
      my $filesystem_path  = shift;
      my $lockfile_name;
    
      $filesystem_path =~ s#/#_#g;
      $filesystem_path =~ s# #_#g;
    
      if ($hide_warning_lockfile eq "yes") {
        $lockfile_name = "." . $program_name . "_warning_lock" . $filesystem_path;
      }
      else {
        $lockfile_name = $program_name . "_warning_lock" . $filesystem_path;
      }
    
      return ($lockfile_name);
    
    }
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Save the warning lockfile
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    # Creates the locking file in the format of:
    # / are converted to underscores for mount point.
    #
    #
    # -rwxr-x---. 1 user user  9211 Feb 21 13:46 df.pl*
    # -rw-rw-r--. 1 user user     0 Feb 21 13:47 .df_warning_lock_boot
    
    
    sub write_warning_lockfile {
      my $lockfile_name  = shift;
      my $lockfile_directory = "./";
    
      # Check if the $warning_lock_directory has been set.
      # If so use it instead of the current directory.
      if ( $warning_lock_directory) {
       $lockfile_directory = $warning_lock_directory;
      }
    
      # Check for the warning lockfile.
      # If it already exists exit.
      if ( -e "${lockfile_directory}${lockfile_name}" ) {
        return;
      }
    
      open (WARNING_LOCKFILE, '>', ${lockfile_directory}.${lockfile_name}) or $formated_report .= "nUnable to save warning lockfile for ${lockfile_directory}${lockfile_name}n Warnings will be sent out every time the script runs.nn";
      close (WARNING_LOCKFILE);
    }
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Check for the warning lockfile
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    sub check_for_warning_lockfile {
    
      my $lockfile_name  = shift;
      my $lockfile_directory = "./";
    
      # Check if the $warning_lock_directory has been set.
      # If so use it instead of the current directory.
      if ( $warning_lock_directory) {
       $lockfile_directory = $warning_lock_directory;
      }
    
      # Check for the warning lockfile.
      if ( -e "${lockfile_directory}${lockfile_name}" ) {
        return 1;
      }
      else {
        return 0;
      }
    }
    
    
    
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Remove the warning lockfile
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    
    sub remove_warning_lockfile {
      my $lockfile_name  = shift;
      my $lockfile_directory = "./";
    
      # Check if the $warning_lock_directory has been set.
      # If so use it instead of the current directory.
      if ( $warning_lock_directory) {
       $lockfile_directory = $warning_lock_directory;
      }
    
      # If the file doesn't exist just exit.
      if (! -e "${lockfile_directory}${lockfile_name}" ) {
        return;
      }
    
      # Remove the warning lockfile.
      `$command_find ${lockfile_directory}${lockfile_name} -mtime +${number_of_days_before_next_warning} -type f -exec $command_rm -f {} \;`;
    }
    
    # Run the main routine.
    &Start;
    
    #>>>>>>>>>>>>>
    #> Main Start
    #>>>>>>>>>>>>>
    
    sub Start {
    
      #declare all major variables used in this subroutine.
      local (%filesystem_info, $TimeStamp, $Hostname, $formated_report, $warning_duplicate_check, $critical_duplicate_check, $program_name);
    
      # Obtain configuration from a file with a name inferred from this
      # script's name.
      ($program_name) = split(/./, basename($0));
      my $program_full_name =basename($0);
    
      # if you don not wish to use XML::Simple comment out next line..
      $config = XMLin("${program_name}.xml", SuppressEmpty => 'undef');
    
      # if you don not wish to use XML::Simple configure variable directly here.
      # if you don't use the XML config file you must place a "" in front of the
      # "@" in your email address so it is not interpreted as an array variable.
      # ex: local $mail_to                            = "[email protected]";
    
      local $command_date                       = $config->{'command_date'};
      local $command_df                         = $config->{'command_df'};
      local $command_find                       = $config->{'command_find'};
      local $command_hostname                   = $config->{'command_hostname'};
      local $command_rm                         = $config->{'command_rm'};
      local $command_sendmail                   = $config->{'command_sendmail'};
      local $warning_percent_used               = $config->{'warning_percent_used'};
      local $critical_percent_used              = $config->{'critical_percent_used'};
      local $number_of_days_before_next_warning = $config->{'number_of_days_before_next_warning'};
      local $warning_lock_directory             = $config->{'warning_lock_directory'};
      local $hide_warning_lockfile              = $config->{'hide_warning_lockfile'};
      local $Include_Hostname_In_Subject        = $config->{'Include_Hostname_In_Subject'};
      local $mail_to                            = $config->{'mail_to'};
      local $mail_from                          = $config->{'mail_from'};
      local $mail_subject_prefix                = $config->{'mail_subject_prefix'};
      local $mail_subject_postfix               = $config->{'mail_subject_postfix'};
      local $mail_x_mailer                      = $config->{'mail_x_mailer'};
    
    
      # Get the hostname
      local $Hostname = `$command_hostname -f`;
      chomp $Hostname;
    
      # Get the date timestamp
      $TimeStamp = `$command_date`;
      chomp $TimeStamp;
    
      # Do the work
      &get_filesystem_data;
      &format_report_output;
      &send_email_notice;
    
      # uncomment to print report when run.
      #print $formated_report;
    
      #End the program
      exit;
    }
    

Comments are closed.