Skip to content

Instantly share code, notes, and snippets.

@ryanbarrett
Last active July 21, 2016 21:52
Show Gist options
  • Save ryanbarrett/34a852e7401d8c0d94d3265d8ffb7a59 to your computer and use it in GitHub Desktop.
Save ryanbarrett/34a852e7401d8c0d94d3265d8ffb7a59 to your computer and use it in GitHub Desktop.
Nagios script to check file size with human readable input and output (in python). Similar to ./check_files.pl -F file.txt -s 5000000,10000000
import argparse,os
#Return OK, Warning, or Critical for nagios to parse.
argparser = argparse.ArgumentParser(description='Nagios script to check file size with human readable input and output (in python). Similar to ./check_files.pl -F file.txt -s 5000000,10000000',epilog="Thanks, Hope you like it. -Ryan")
argparser.add_argument('--missingfileok','-m',action='store_true',help='If the file does not exist return OK.')
argparser.add_argument('--file','-f',type=str,required=True,help='Pass in full path and file name i.e. --file /test/123/filename.txt ')
argparser.add_argument('--critical','-c',type=str,required=True,help='K,M, or G, defaults to bytes')
argparser.add_argument('--warning','-w',type=str,required=True,help='K,M, or G, defaults to bytes')
args = argparser.parse_args()
suffixes = ['K', 'M', 'G', 'T']
def CheckFileExists(pathandfilename):
return os.path.isfile(pathandfilename)
def GetFileSize(pathandfilename):
return os.path.getsize(pathandfilename)
def ConvertFileSizeToBKMGT(size):
sizes = {}
sizes["B"] = size # occupies suffixindex 0
suffixIndex = 0
while suffixIndex < 4:
suffixIndex += 1 # increment the index of the suffix
size = size / 1024.0 # apply the division
sizes[suffixes[suffixIndex-1]] = size
return sizes
def RepresentsFloat(s):
try:
float(s)
return True
except ValueError:
return False
def SplitValueandSuffix(worcinput):
if RepresentsFloat(worcinput):
return worcinput,"B"
else:
inputvalue = worcinput.strip(worcinput[-1])
if RepresentsFloat(inputvalue) and worcinput[-1].upper() in suffixes:
return float(inputvalue), worcinput[-1].upper()
def main(args):
if CheckFileExists(args.file):
filesizeinbytes = GetFileSize(args.file)
bkmgt = ConvertFileSizeToBKMGT(filesizeinbytes)
warning = SplitValueandSuffix(args.warning) # for 20K returns a tuple (20,K)
critical = SplitValueandSuffix(args.critical)
if bkmgt[critical[1]] >= critical[0]:
print("Critical - File Size is ", round(bkmgt[critical[1]], 2), critical[1])
elif bkmgt[warning[1]] >= warning[0]:
print("Warning - File Size is ",round(bkmgt[warning[1]],2), warning[1])
else:
print("OK - File Size is ", round(bkmgt[warning[1]],2), warning[1])
elif args.missingfileok:
print("OK - Missing File")
else:
print("Critical - Missing File")
if __name__ == "__main__":
try:
main(args)
except(Exception):
raise
else:
pass
finally:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment