#!/usr/bin/env bash set -Eeuo pipefail REPO="https://gitea.vourx.com/sharky/Proxmox-und-GuestUpdater" RAW="${REPO}/raw/branch/main" UPDATER="/usr/local/sbin/pve-guest-update" CONFIG="/etc/pve-guest-update.conf" SERVICE="/etc/systemd/system/pve-guest-update.service" TIMER="/etc/systemd/system/pve-guest-update.timer" LOGFILE="/var/log/pve-guest-update.log" NOTIFY_MATCHER="proxmox-updater" NOTIFY_TEMPLATE="proxmox-updater" usage() { cat <<'EOF' Proxmox Guest Updater - Installer Aufruf: install.sh install.sh --uninstall install.sh --clear-excludes install.sh --help Optionen: --uninstall Updater, Timer, Service, Konfiguration und eigene Notification-Hilfsdateien entfernen. --clear-excludes Alle Gast-Ausschlüsse aus der vorhandenen Konfiguration entfernen. --help Diese Hilfe anzeigen. Bei interaktiver Installation kann die Ausschlussliste zusätzlich mit "keine", "none" oder "-" vollständig geleert werden. EOF } uninstall_updater() { echo echo "Entferne Proxmox Guest Updater ..." systemctl disable --now pve-guest-update.timer >/dev/null 2>&1 || true systemctl stop pve-guest-update.service >/dev/null 2>&1 || true rm -f "$TIMER" "$SERVICE" "$UPDATER" "$CONFIG" rm -f \ "/etc/pve/notification-templates/default/${NOTIFY_TEMPLATE}-subject.txt.hbs" \ "/etc/pve/notification-templates/default/${NOTIFY_TEMPLATE}-body.txt.hbs" \ "/etc/pve/notification-templates/default/${NOTIFY_TEMPLATE}-body.html.hbs" if command -v pvesh >/dev/null 2>&1; then pvesh delete "/cluster/notifications/matchers/${NOTIFY_MATCHER}" >/dev/null 2>&1 || true fi systemctl daemon-reload systemctl reset-failed pve-guest-update.service >/dev/null 2>&1 || true echo "Proxmox Guest Updater wurde entfernt." echo echo "Das bisherige Log wurde absichtlich behalten:" echo " $LOGFILE" echo echo "Zum Löschen des Logs:" echo " rm -f $LOGFILE" } clear_excludes() { if [[ ! -f "$CONFIG" ]]; then echo "FEHLER: Keine vorhandene Installation/Konfiguration gefunden." exit 1 fi if grep -q '^EXCLUDE_GUESTS=' "$CONFIG"; then sed -i 's/^EXCLUDE_GUESTS=.*/EXCLUDE_GUESTS=""/' "$CONFIG" else printf '\nEXCLUDE_GUESTS=""\n' >> "$CONFIG" fi chmod 600 "$CONFIG" echo "Alle Gast-Ausschlüsse wurden entfernt." } case "${1:-}" in --uninstall) if [[ $EUID -ne 0 ]]; then echo "FEHLER: Bitte als root ausführen." exit 1 fi uninstall_updater exit 0 ;; --clear-excludes) if [[ $EUID -ne 0 ]]; then echo "FEHLER: Bitte als root ausführen." exit 1 fi clear_excludes exit 0 ;; --help|-h) usage exit 0 ;; "") ;; *) echo "Unbekannte Option: $1" echo usage exit 1 ;; esac # ------------------------------------------------------------ # Grundprüfungen # ------------------------------------------------------------ if [[ $EUID -ne 0 ]]; then echo echo "FEHLER: Bitte als root auf dem Proxmox-Host ausführen." exit 1 fi if ! command -v pveversion >/dev/null 2>&1; then echo echo "FEHLER: Proxmox VE wurde auf diesem System nicht erkannt." exit 1 fi if ! command -v curl >/dev/null 2>&1; then echo "curl fehlt - wird installiert ..." apt-get update apt-get install -y curl fi # ------------------------------------------------------------ # Standardwerte # ------------------------------------------------------------ UPDATE_HOST="yes" UPDATE_LXC="yes" UPDATE_VMS="yes" UPDATE_STOPPED="no" AUTO_REBOOT_HOST="yes" EXCLUDE_GUESTS="" NOTIFY_ENABLED="no" NOTIFY_TARGET="" DAY="7" DAY_SYSTEMD="Sun" DAY_NAME="Sonntag" UPDATE_TIME="04:00" EXISTING_INSTALL="no" # ------------------------------------------------------------ # Vorhandene Installation einlesen # ------------------------------------------------------------ if [[ -f "$CONFIG" ]]; then EXISTING_INSTALL="yes" # Vorhandene Konfiguration laden # shellcheck disable=SC1090 source "$CONFIG" # Fehlende Werte absichern UPDATE_HOST="${UPDATE_HOST:-yes}" UPDATE_LXC="${UPDATE_LXC:-yes}" UPDATE_VMS="${UPDATE_VMS:-yes}" UPDATE_STOPPED="${UPDATE_STOPPED:-no}" AUTO_REBOOT_HOST="${AUTO_REBOOT_HOST:-yes}" EXCLUDE_GUESTS="${EXCLUDE_GUESTS:-}" NOTIFY_ENABLED="${NOTIFY_ENABLED:-no}" NOTIFY_TARGET="${NOTIFY_TARGET:-}" # Vorhandenen systemd-Zeitplan auslesen if [[ -f "$TIMER" ]]; then ONCALENDAR="$( sed -n 's/^[[:space:]]*OnCalendar=//p' "$TIMER" | head -n1 )" if [[ "$ONCALENDAR" =~ ^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[[:space:]]+\*-\*-\*[[:space:]]+([0-9]{2}:[0-9]{2}):[0-9]{2}$ ]]; then DAY_SYSTEMD="${BASH_REMATCH[1]}" UPDATE_TIME="${BASH_REMATCH[2]}" case "$DAY_SYSTEMD" in Mon) DAY="1"; DAY_NAME="Montag" ;; Tue) DAY="2"; DAY_NAME="Dienstag" ;; Wed) DAY="3"; DAY_NAME="Mittwoch" ;; Thu) DAY="4"; DAY_NAME="Donnerstag" ;; Fri) DAY="5"; DAY_NAME="Freitag" ;; Sat) DAY="6"; DAY_NAME="Samstag" ;; Sun) DAY="7"; DAY_NAME="Sonntag" ;; esac fi fi fi clear echo "============================================================" echo " Proxmox Guest Updater" echo " Installation" echo "============================================================" echo echo "Host: $(hostname)" echo "Proxmox: $(pveversion)" echo if [[ "$EXISTING_INSTALL" == "yes" ]]; then echo "Vorhandene Installation erkannt." echo echo "Aktuelle Einstellungen:" echo echo " Proxmox-Host aktualisieren: $UPDATE_HOST" echo " LXC automatisch aktualisieren: $UPDATE_LXC" echo " VMs automatisch aktualisieren: $UPDATE_VMS" echo " Gestoppte Gäste starten: $UPDATE_STOPPED" echo " Automatischer Host-Reboot: $AUTO_REBOOT_HOST" echo " Benachrichtigungen: $NOTIFY_ENABLED" if [[ "$NOTIFY_ENABLED" == "yes" ]]; then echo " Notification-Target: ${NOTIFY_TARGET:-nicht gesetzt}" fi echo " Zeitplan: $DAY_NAME $UPDATE_TIME Uhr" echo " Ausgeschlossene Gäste: ${EXCLUDE_GUESTS:-keine}" echo echo "Mit Enter wird jeweils die vorhandene Einstellung übernommen." echo fi # ------------------------------------------------------------ # Hilfsfunktionen # ------------------------------------------------------------ ask_yes_no() { local prompt="$1" local current="$2" local answer while true; do if [[ "$current" == "yes" ]]; then read -r -p "$prompt [J/n]: " answer /dev/null 2>&1 || ! command -v python3 >/dev/null 2>&1; then echo "Backup-Zeitplanprüfung: nicht möglich (pvesh/python3 fehlt)." return fi backup_json="$(pvesh get /cluster/backup --output-format json 2>/dev/null || true)" if [[ -z "$backup_json" || "$backup_json" == "[]" ]]; then echo "Backup-Zeitplanprüfung: keine Proxmox-Backup-Jobs gefunden." return fi result="$( BACKUP_JSON="$backup_json" python3 - "$DAY_SYSTEMD" "$UPDATE_TIME" <<'PY' import json, os, re, sys upd_day = sys.argv[1].lower() upd_time = sys.argv[2] jobs = json.loads(os.environ.get("BACKUP_JSON", "[]")) daynum = {"mon":0,"tue":1,"wed":2,"thu":3,"fri":4,"sat":5,"sun":6} ud = daynum[upd_day[:3]] uh, um = map(int, upd_time.split(":")) u = ud*1440 + uh*60 + um def days_from_expr(expr): expr = expr.lower().strip() if not expr or expr in ("*", "daily"): return set(range(7)) out=set() for part in re.split(r"[,;]", expr): part=part.strip() if ".." in part: a,b=part.split("..",1) a=daynum.get(a[:3]); b=daynum.get(b[:3]) if a is None or b is None: continue i=a while True: out.add(i) if i==b: break i=(i+1)%7 else: d=daynum.get(part[:3]) if d is not None: out.add(d) return out conflicts=[] unknown=[] for job in jobs: if str(job.get("enabled","1")).lower() in ("0","false","no"): continue sched=str(job.get("schedule","")).strip() if not sched: continue # Common PVE forms: "sun 02:00", "mon..fri 03:00", "02:00" m=re.search(r"(?:(?P[A-Za-z.,]+(?:\.\.[A-Za-z]+)?)\s+)?(?P[0-2]?\d):(?P[0-5]\d)$", sched) if not m: unknown.append((job.get("id","?"), sched)) continue days=days_from_expr(m.group("days") or "*") bh=int(m.group("h")); bm=int(m.group("m")) for d in days: b=d*1440+bh*60+bm diff=(b-u+7*1440)%(7*1440) if diff>7*1440//2: diff-=7*1440 # Potential overlap window: backup starts within 2h before/after updater. if abs(diff) <= 120: conflicts.append((job.get("id","?"), sched, diff)) break if conflicts: print("WARN") for jid,sched,diff in conflicts: if diff == 0: rel="gleiche Startzeit" elif diff < 0: rel=f"{abs(diff)} Min. vor dem Updater" else: rel=f"{diff} Min. nach dem Updater" print(f" - Backup-Job {jid}: {sched} ({rel})") elif unknown: print("UNKNOWN") for jid,sched in unknown: print(f" - Backup-Job {jid}: {sched}") else: print("OK") PY )" case "$result" in WARN*) echo "WARNUNG: Mögliche zeitliche Überschneidung mit Proxmox-Backups:" printf '%s\n' "$result" | tail -n +2 echo echo "Geprüft wird ein Sicherheitsfenster von ±2 Stunden um den Updater-Start." echo "Die tatsächliche Backup-Dauer kann Proxmox aus dem Zeitplan nicht vorhersagen." echo "Der Updater wartet zusätzlich auf ein bereits laufendes vzdump-Backup." ;; UNKNOWN*) echo "Backup-Zeitplanprüfung: einige Zeitpläne konnten nicht automatisch verglichen werden:" printf '%s\n' "$result" | tail -n +2 ;; *) echo "Backup-Zeitplanprüfung: keine Proxmox-Backup-Startzeit innerhalb ±2 Stunden." ;; esac echo "Hinweis: Backups, die innerhalb einer VM/eines LXC selbst laufen," echo "kann der Proxmox-Host nicht allgemein erkennen." } # ------------------------------------------------------------ # Einstellungen abfragen # ------------------------------------------------------------ ask_yes_no "Proxmox-Host automatisch aktualisieren?" "$UPDATE_HOST" UPDATE_HOST="$REPLY" echo ask_yes_no "Laufende LXC-Container automatisch aktualisieren?" "$UPDATE_LXC" UPDATE_LXC="$REPLY" echo ask_yes_no "Linux-VMs automatisch aktualisieren?" "$UPDATE_VMS" UPDATE_VMS="$REPLY" echo ask_yes_no "Gestoppte Gäste für Updates automatisch starten?" "$UPDATE_STOPPED" UPDATE_STOPPED="$REPLY" echo ask_yes_no "Proxmox automatisch neu starten, wenn erforderlich?" "$AUTO_REBOOT_HOST" AUTO_REBOOT_HOST="$REPLY" echo ask_yes_no "Proxmox-Benachrichtigung nach Update-Läufen senden?" "$NOTIFY_ENABLED" NOTIFY_ENABLED="$REPLY" if [[ "$NOTIFY_ENABLED" == "yes" ]]; then echo echo "Vorhandene Proxmox-Notification-Targets:" TARGETS="$(pvesh get /cluster/notifications/targets --output-format json 2>/dev/null | grep -oE '"name":"[^"]+"' | sed -E 's/^"name":"([^"]+)"$/\1/' | sort -u || true)" if [[ -z "$TARGETS" ]]; then echo " Keine Targets gefunden." echo " Benachrichtigungen werden deaktiviert." NOTIFY_ENABLED="no" NOTIFY_TARGET="" else while IFS= read -r target; do [[ -n "$target" ]] && echo " - $target" done <<< "$TARGETS" # Eingebautes Proxmox-Fallback nicht als bevorzugtes Ziel behandeln. # Wenn genau ein anderes Target existiert, automatisch verwenden. CUSTOM_TARGETS="$(printf '%s\n' "$TARGETS" | grep -Fxv 'mail-to-root' || true)" CUSTOM_COUNT="$(printf '%s\n' "$CUSTOM_TARGETS" | sed '/^$/d' | wc -l)" if [[ "$CUSTOM_COUNT" -eq 1 ]]; then NOTIFY_TARGET="$(printf '%s\n' "$CUSTOM_TARGETS" | sed '/^$/d' | head -n1)" echo echo "Notification-Target automatisch gewählt: $NOTIFY_TARGET" elif [[ "$CUSTOM_COUNT" -eq 0 ]]; then # Nur mail-to-root vorhanden. Das ist ein gültiges Proxmox-Ziel. NOTIFY_TARGET="mail-to-root" echo echo "Notification-Target automatisch gewählt: $NOTIFY_TARGET" else echo echo "Mehrere benutzerdefinierte Targets vorhanden." while true; do read -r -p "Notification-Target [${NOTIFY_TARGET:-keins}]: " NEW_TARGET "$CONFIG" < "$SERVICE" <<'EOF' [Unit] Description=Proxmox Guest Updater After=network-online.target pve-cluster.service Wants=network-online.target [Service] Type=oneshot ExecStart=/usr/local/sbin/pve-guest-update Nice=10 IOSchedulingClass=best-effort IOSchedulingPriority=7 TimeoutStartSec=infinity EOF # ------------------------------------------------------------ # systemd Timer # ------------------------------------------------------------ cat > "$TIMER" <