Skip to content

Instantly share code, notes, and snippets.

@antonlindstrom
Created December 7, 2012 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonlindstrom/4231723 to your computer and use it in GitHub Desktop.
Save antonlindstrom/4231723 to your computer and use it in GitHub Desktop.
Nagios check for checking size of a file
#!/usr/bin/perl
### check_file_size.pl
# Based on check_backup.pl by Nathan Vonnahme
#
use strict;
use warnings;
use File::stat;
use Getopt::Long;
use vars qw($VERSION $PROGNAME $file $size $help);
$VERSION = '1.0';
# get the base name of this script for use in the examples
use File::Basename;
$PROGNAME = basename($0);
# II. Usage/Help
sub help() {
print "Usage: $PROGNAME
[ -f|--file=<path/to/file> ]
[ -s|--size=<max size in MB> ]
Examples:
$PROGNAME -f /var/log/syslog -s 2048
Check that /var/log/syslog exists, is below 2048 MB.
";
}
# Getopt::Long
GetOptions(
'file|f=s', \$file,
'size|s=s', \$size,
'help|h=s', \$help);
# Print help if nothing is defined
unless (defined($file) && defined($size)) {
help();
exit -1;
}
# Check the backup file.
unless (-e $file) {
print "File $file doesn't exist";
exit 2;
}
# Calculate
my $mtime = File::stat::stat($file)->mtime;
my $age_in_hours = (time - $mtime) / 60 / 60;
my $size_in_mb = (-s $file) / 1_000_000;
my $message = sprintf "Backup exists, %.0f hours old, %.1f MB.\n",
$age_in_hours, $size_in_mb;
# Print output
print $message;
# Exit with error msgs
if ( $size_in_mb > $size ) {
exit 2;
} else {
exit 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment