nagios-scripts/check-systemctl-service.sh
Jeroen De Meerleer e849092a4d
Add script name and directory variables to check-systemctl-service.sh
This commit adds two new variables, script_name and script_dir, to the check-systemctl-service.sh file. These variables are used to store the name of the script and its directory path respectively.
2023-06-01 16:09:07 +02:00

96 lines
2.1 KiB
Bash

#!/bin/bash
#
#/
#/ Usage:
#/ check-systemctl-service.sh <unit-file>
#/
#/ Options:
#/ -u, --user Check for running within current user
#/
#/ Checks if a systemd unit is active
#/
#/ Exit Codes:
#/ 0 Everything OK
#/ 2 Unit is not running
#/ 3 Unknown status
#/
Usage() {
grep '^#/' "${script_dir}/${script_name}" | sed 's/^#\/\w*//'
}
GetOptions() {
# https://stackoverflow.com/a/29754866
OPTIONS=u
LONGOPTS=user
# -use ! and PIPESTATUS to get exit code with errexit set
# -temporarily store output to be able to check for errors
# -activate quoting/enhanced mode (e.g. by writing out “--options”)
# -pass arguments only via -- "$@" to separate them correctly
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
# e.g. return value is 1
# then getopt has complained about wrong arguments to stdout
Usage
exit 2
fi
# read getopt's output this way to handle the quoting right:
eval set -- "$PARSED"
# now enjoy the options in order and nicely split until we see --
while true; do
case "$1" in
-u|--user)
user='--user'
shift 1
;;
--)
shift
break
;;
*)
echo "SERVICE UNKNOWN - ${1} is not a valid parameter"
exit 3
;;
esac
done
if [ -z ${1+x} ]; then
echo "SERVICE UNKNOWN - Unitfile not given"
exit 3
else
service=${1}
fi
}
user=''
service=''
LC_NUMERIC="C"
script_name=$(basename "${0}")
script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
GetOptions "$@"
if [[ $(systemctl ${user} list-unit-files "${service}*" | wc -l) -gt 3 ]]; then
result=$(systemctl ${user} is-active ${service})
else
result='inexistent'
fi
if [[ $result == 'active' ]]; then
rval=0
rmsg="OK"
elif [[ $result == 'inexistent' ]]; then
rval=1
rmsg="WARNING"
else
rval=2
rmsg="CRITICAL"
fi
echo "SERIVCE ${rmsg} - Service $service $result"
exit $rval