#!/usr/bin/env bash # usage usage() { SYSTEMD_CHECK_USAGE=$(cat <'. EOF ) echo "$SYSTEMD_CHECK_USAGE"; } set -e; # vars and defaults SYSTEMD_CHECK_LIST_FILE="$HOME/.systemd_check.list" SYSTEMD_CHECK_MAIL_ENABLED=fase SYSTEMD_CHECK_MAIL_ADDRESS="" SYSTEMD_CHECK_HOSTNAME=$(hostname) SYSTEMD_CHECK_USER=$(whoami) SYSTEMD_CHECK_SERVICES=() # check for config file source_config() { local config=$1; local configFallback=$2; if [[ ! -f "$config" ]]; then if [[ ! -f "$configFallback" ]]; then echo "No config file specified and could not find default in '$configFallback'!"; echo ""; usage; exit 1; else config=$configFallback; fi fi set -a; source "$config"; set +a; } source_config "$1" "$HOME/.systemd_check.conf" if [ ! -f $SYSTEMD_CHECK_LIST_FILE ]; then echo "$SYSTEMD_CHECK_LIST_FILE doesn't exist. Add a file which holds one systemd service or timer per line."; echo ""; usage; exit 1; fi echo "Scanning $SYSTEMD_CHECK_LIST_FILE for services..."; while IFS='' read -r line || [[ -n "$line" ]]; do SYSTEMD_CHECK_SERVICES+=("$line") echo "-> Found $line"; done < "$SYSTEMD_CHECK_LIST_FILE" # get status for a service function checkService() { local SERVICE=$1; local MESSAGE="$SERVICE is not running for user $SYSTEMD_CHECK_USER"; local COMMAND="systemctl is-active --quiet $SERVICE"; if [ "$(id -u)" != "0" ]; then local COMMAND="systemctl --user is-active --quiet $SERVICE"; fi if ! $($COMMAND); then local SUBJECT="[systemd $SYSTEMD_CHECK_HOSTNAME for $SYSTEMD_CHECK_USER] CRITICAL $SERVICE"; echo "-> $SUBJECT: $MESSAGE"; if [ "$SYSTEMD_CHECK_MAIL_ENABLED" = true ]; then echo $MESSAGE|mailx -Ssendwait -s "$SUBJECT" $SYSTEMD_CHECK_MAIL_ADDRESS; fi fi return; } # execute check for defined SYSTEMD_CHECK_SERVICES for service in "${SYSTEMD_CHECK_SERVICES[@]}"; do echo "Checking $service..."; checkService "$service" done