Files
shell_ntfy_remote_shutdown/shell_ntfy_remote_shutdown.sh
2026-05-22 15:17:39 +02:00

134 lines
2.6 KiB
Bash

#!/bin/bash
set -u
# Pfad zur .env-Datei dynamisch ermitteln
ENV_FILE="$(dirname "$(realpath "$0")")/$(basename "$0" .sh).env"
# Prüfen, ob die .env-Datei existiert
if [[ ! -f "$ENV_FILE" ]]; then
echo "Fehler: Konfigurationsdatei $ENV_FILE nicht gefunden."
exit 1
fi
# .env-Datei laden
source "$ENV_FILE"
SSH_TARGET="$SSH_USER@$SSH_HOST"
echo "Starte Shutdown von $SSH_TARGET ..."
# Mögliche Shutdown-Kommandos für alte QNAPs / Linux-Systeme
SHUTDOWN_COMMANDS=(
"poweroff"
"/sbin/poweroff"
"shutdown now"
"/sbin/shutdown now"
"halt"
"/sbin/halt"
"init 0"
)
shutdown_success=false
successful_command=""
ssh_error=""
for cmd in "${SHUTDOWN_COMMANDS[@]}"; do
echo "Teste: $cmd"
ssh_output=$(
ssh \
-i "$SSH_KEY" \
-o ConnectTimeout=10 \
-o BatchMode=yes \
-o StrictHostKeyChecking=no \
"$SSH_TARGET" "$cmd" 2>&1
)
exit_code=$?
echo "$ssh_output"
# Erfolgreich ausgeführt
if [[ $exit_code -eq 0 ]]; then
echo "Shutdown erfolgreich mit: $cmd"
shutdown_success=true
successful_command="$cmd"
break
fi
# Viele Systeme schließen SSH sofort beim Shutdown
if echo "$ssh_output" | grep -qiE "connection closed|broken pipe|connection reset"; then
echo "SSH-Verbindung beim Shutdown getrennt: $cmd"
shutdown_success=true
successful_command="$cmd"
break
fi
ssh_error="$ssh_output"
sleep 2
done
# NTFY Nachricht vorbereiten
if [[ "$shutdown_success" == true ]]; then
TITLE="Backups beendet"
MESSAGE="QNAP wird heruntergefahren.
Server: \`$SERVER_NAME\`"
TAGS="checkered_flag"
PRIORITY="default"
else
TITLE="QNAP Shutdown fehlgeschlagen"
MESSAGE="Das QNAP konnte nicht heruntergefahren werden.
Server: \`$SERVER_NAME\`
SSH Fehler: \`$ssh_error\`"
TAGS="warning"
PRIORITY="high"
fi
# JSON Payload sicher erzeugen
JSON_PAYLOAD=$(jq -n \
--arg topic "Duplicati" \
--arg title "$TITLE" \
--arg message "$MESSAGE" \
--arg url "$DUPLICATI_URL" \
'{
topic: $topic,
title: $title,
message: $message,
click: "",
actions: [
{
action: "view",
label: "Duplicati öffnen",
url: $url
}
]
}'
)
# Debug optional
echo "$JSON_PAYLOAD"
# NTFY senden
curl -s -X POST "$NTFY_URL" \
-H "Authorization: Bearer $AUTH_TOKEN" \
-H "Priority: $PRIORITY" \
-H "Tags: $TAGS" \
${ICON:+-H "Icon: $ICON"} \
-H "Markdown: yes" \
-H "Content-Type: application/json" \
-d "$JSON_PAYLOAD"
# Passender Exitcode
if [[ "$shutdown_success" == true ]]; then
exit 0
else
exit 1
fi