Files
portfolio/infra-run/scripts/bash/service_check.sh
T

61 lines
1.2 KiB
Bash
Executable File

#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
services=("$@")
service_exists() {
local service="$1"
systemctl list-unit-files "${service}.service" --no-legend 2>/dev/null | awk '{print $1}' | grep -qx "${service}.service"
}
pick_default_scheduler() {
if service_exists cron; then
printf 'cron'
elif service_exists crond; then
printf 'crond'
else
printf 'cron'
fi
}
pick_default_ssh() {
if service_exists sshd; then
printf 'sshd'
elif service_exists ssh; then
printf 'ssh'
else
printf 'sshd'
fi
}
if ! command -v systemctl >/dev/null 2>&1; then
printf 'CRITICAL: systemctl command not available; cannot check services\n' >&2
exit 1
fi
if (( ${#services[@]} == 0 )); then
services=("$(pick_default_ssh)" "$(pick_default_scheduler)")
fi
status=0
for service in "${services[@]}"; do
if ! service_exists "$service"; then
printf 'CRITICAL: %s service not found\n' "$service"
status=1
continue
fi
if systemctl is-active --quiet "$service"; then
printf 'OK: %s is active\n' "$service"
else
state="$(systemctl is-active "$service" 2>/dev/null || true)"
printf 'CRITICAL: %s is %s\n' "$service" "${state:-unknown}"
status=1
fi
done
exit "$status"