From e8989884ed193ff9cf81439d608afce4c149325c Mon Sep 17 00:00:00 2001 From: Danny de Kooker Date: Sat, 16 Sep 2023 16:24:17 +0200 Subject: [PATCH] added Linux - Automatic Services Monitor script --- .../Linux - Automatic Services Monitor.sh | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Check_scripts/Linux - Automatic Services Monitor.sh diff --git a/Check_scripts/Linux - Automatic Services Monitor.sh b/Check_scripts/Linux - Automatic Services Monitor.sh new file mode 100644 index 0000000..bc814ad --- /dev/null +++ b/Check_scripts/Linux - Automatic Services Monitor.sh @@ -0,0 +1,69 @@ +#!/bin/bash +# Usage: "Linux - Automatic Services Monitor.sh" +# +# Description: +# This script is used from inside of Tactical RMM instances to monitor all automatic starting services. +# This script should be deployed as a check script. +# +# Options: +# +# Author: D. de Kooker (info@dcomputers.nl) +# Sources: n/a Created with the help of openai +# Changelog : +# 16-09-2023 - Initial script + +# Array of services to exclude from monitoring +# // EXCLUDE=("service_to_exclude1" "service_to_exclude2") +EXCLUDE=("") + +# Function to check the status of a service and display its last error message +check_service_status() { + service_name="$1" + systemctl is-active --quiet "$service_name" + if [ $? -eq 0 ]; then + return 0 # Service is running + else + return 1 # Service is not running + fi +} + +# Function to get and display the last error message from the service's status log +display_last_error_message() { + service_name="$1" + last_error_message=$(journalctl -n 1 -u "$service_name" --no-pager --quiet) + if [ -n "$last_error_message" ]; then + echo "Last error message for $service_name:" + echo "$last_error_message" + fi +} + +# Array to store the names of stopped services +STOPPED_SERVICES=() + +# Main loop to monitor all services except excluded ones +# echo "Monitoring all services set to start automatically..." + +# Get the list of all enabled services +enabled_services=$(systemctl list-units --type=service --state=active --no-legend | awk '{print $1}') + +for service in $enabled_services; do + # Check if the service is in the exclusion list + if [[ ! " ${EXCLUDE[@]} " =~ " $service " ]]; then + if ! check_service_status "$service"; then + STOPPED_SERVICES+=("$service") + fi + fi +done + +if [ ${#STOPPED_SERVICES[@]} -eq 0 ]; then + echo "All services are running." + exit 0 +else + echo "Services in error/stopped state:" + for stopped_service in "${STOPPED_SERVICES[@]}"; do + echo "$stopped_service" + display_last_error_message "$stopped_service" + echo "" + done + exit 1 +fi \ No newline at end of file