-
Notifications
You must be signed in to change notification settings - Fork 9
/
check_file.py
99 lines (86 loc) · 2.71 KB
/
check_file.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
"""
This script tests if the first line of a specified file contains a specified
content. This script is meant to be invoked by nagios/icinga.
REQUIREMENTS
This script requires python-argparse and is meant to be run on *nix-systems.
COPYRIGHT
Copyright 2011-2016 - Kumina B.V./Rutger Spiertz ([email protected]), this script
is licensed under the GNU GPL version 3 or higher.
"""
# Import the classes needed
import argparse
from sys import exit
from os import path
# Define and initialize global variables
exit_ok = 0
exit_warn = 1
exit_crit = 2
exit_err = 3
msg = ''
parser = argparse.ArgumentParser(
description=('This script tests if the first line of a specified file'
' contains a specified content. This script is meant to be'
' invoked by nagios/icinga.'))
parser.add_argument(
'-f', '--filename', action='store', required=True,
help='The file (with path) to check.')
parser.add_argument(
'-c', '--content', action='store',
help='The content that is expected to be on the first line of the file.')
parser.add_argument(
'-n', '--negate', action='store_true',
help=('Specifies that the file should not exist, the first line is'
' returned if it does exist.'))
parser.add_argument(
'-w', '--warn', action='store_true',
help='Warn instead of crit when the files existence or content is wrong.')
def quit(state):
global msg
if state == exit_warn:
msg = 'WARNING: ' + msg
elif state == exit_crit:
msg = 'CRITICAL: ' + msg
else:
msg = 'OK: ' + msg
print msg
exit(state)
def addToMsg(newString):
global msg
if msg != '':
msg += ' %s' % newString
else:
msg += '%s' % newString
# Script starts here...
args = parser.parse_args()
if args.warn:
exit_crit = exit_warn
# Get the file content
if path.isfile(args.filename):
try:
f = open(args.filename, 'r')
except:
addToMsg("%s can't be read." % args.filename)
quit(exit_crit)
fileContent = f.readline().strip()
f.close()
else:
if args.negate:
addToMsg("%s doesn't exist." % args.filename)
quit(exit_ok)
else:
addToMsg("%s doesn't exist." % args.filename)
quit(exit_crit)
if args.negate:
addToMsg('%s' % fileContent)
quit(exit_crit)
elif args.content != None and fileContent != args.content:
addToMsg('the content of %s doesn\'t equal "%s".' % (args.filename,
args.content))
quit(exit_crit)
elif args.content != None and fileContent == args.content:
addToMsg('File is on disk and content is as expected.')
quit(exit_ok)
else:
addToMsg('File is on disk.')
quit(exit_ok)