-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_systemd_service.sh
executable file
·129 lines (109 loc) · 2.34 KB
/
check_systemd_service.sh
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/bin/env bash
# Source: https://github.com/patrikskrivanek/icinga2-check_systemd_service/
VERSION='v1.1.0'
RELEASE_DATE='2019-08-13'
# output codes
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3
PROGRAM=`basename "$0"`
#print help function
print_help() {
echo -n "This plugin checks status of systemd service and also can restart service if is not running.
Returns exit codes based on nagios plugin api standard.
Usage:
$PROGRAM [OPTION]
Options:
[service] name of systemd service for check
--restart restart service if is not running
-V, --version current version of plugin
-h, --help plugin help and usage
Examples:
$PROGRAM apache2
$PROGRAM cron --restart
$PROGRAM mysql
$PROGRAM -V
$PROGRAM --help
version: $VERSION
release: $RELEASE_DATE
"
exit 0
}
#print version function
print_version() {
echo "$VERSION"
exit 0
}
# check "zero" param
([[ -z "$1" ]]) && print_help
case "$1" in
-h|--help)
print_help
;;
-V|--version)
print_version
;;
*)
service="$1"
;;
esac
# arg shift
POSITIONAL=()
while [[ $# -gt 0 ]]
do
case "$2" in
--reload)
RELOAD=YES
shift
;;
--restart)
RESTART=YES
shift
;;
*)
# unknown option, save
POSITIONAL+=("$2")
shift
;;
esac
done
# restore positional parameters
set -- "${POSITIONAL[@]}"
# service check
if [[ -z "$service" ]]; then
echo "WARNING: service name hasn't been set"
exit $STATE_WARNING
fi
status=$(systemctl is-enabled $service 2>/dev/null)
ret=$?
# service does not exist
if [[ -z "$status" ]]; then
echo "ERROR: service $service doesn't exist"
exit $STATE_CRITICAL
fi
# alternative state
if [[ $ret -ne 0 ]]; then
echo "ERROR: service $service is $status"
exit $STATE_CRITICAL
fi
# check if is or is not running
systemctl --quiet is-active $service
if [[ $? -ne 0 ]]; then
if [[ ! -z "$RESTART" ]]; then
systemctl restart $service
if [[ "$?" -eq 0 ]]; then
echo "OK: service restarted"
exit $STATE_OK
else
echo "ERROR: service restart failed"
exit $STATE_CRITICAL
fi
else
echo "ERROR: service $service is not running"
exit $STATE_CRITICAL
fi
else
echo "OK: service $service is running"
exit $STATE_OK
fi