187 lines
6.8 KiB
Python
Executable File
187 lines
6.8 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
|
|
import os
|
|
import sys
|
|
import shutil
|
|
import subprocess
|
|
import ctypes
|
|
import shlex
|
|
import time
|
|
import re
|
|
from pathlib import Path
|
|
from typing import Optional
|
|
|
|
# ----------------------------- Helpers -----------------------------
|
|
|
|
def run(cmd: str, check: bool = False, capture: bool = False) -> subprocess.CompletedProcess:
|
|
"""Führt einen Shell-Befehl aus, loggt ihn und gibt das Ergebnis zurück."""
|
|
print(f"> {cmd}")
|
|
result = subprocess.run(cmd, shell=True, text=True,
|
|
stdout=subprocess.PIPE if capture else None,
|
|
stderr=subprocess.STDOUT if capture else None)
|
|
if capture and result.stdout:
|
|
print(result.stdout.strip())
|
|
if check and result.returncode != 0:
|
|
raise RuntimeError(f"Befehl fehlgeschlagen (Exit {result.returncode}): {cmd}")
|
|
return result
|
|
|
|
def ensure_admin() -> None:
|
|
"""Erhöht bei Bedarf die Rechte via UAC und startet das Skript neu."""
|
|
try:
|
|
if os.name != "nt":
|
|
print("Dieses Skript kann nur unter Windows ausgeführt werden.")
|
|
sys.exit(1)
|
|
if not ctypes.windll.shell32.IsUserAnAdmin():
|
|
script = os.path.abspath(__file__)
|
|
params = ' '.join(shlex.quote(arg) for arg in sys.argv[1:])
|
|
ctypes.windll.shell32.ShellExecuteW(
|
|
None, "runas", sys.executable, f'"{script}" {params}', None, 1
|
|
)
|
|
sys.exit(0)
|
|
except Exception as e:
|
|
print(f"Fehler bei der Anforderung von Administratorrechten: {e}")
|
|
sys.exit(1)
|
|
|
|
# ----------------------------- Processes -----------------------------
|
|
|
|
def stop_process(image_name: str) -> None:
|
|
"""Beendet einen Prozess anhand des Image-Namens (ohne .exe)."""
|
|
run(f'taskkill /IM "{image_name}.exe" /F /T')
|
|
|
|
# ----------------------------- Services -----------------------------
|
|
|
|
_state_re = re.compile(r"STATE\s*:\s*\d+\s+(\w+)", re.IGNORECASE)
|
|
|
|
def service_exists(name: str) -> bool:
|
|
r = run(f'sc.exe query "{name}"', capture=True)
|
|
return r.returncode == 0 and "FAILED" not in (r.stdout or "")
|
|
|
|
def get_service_state(name: str) -> Optional[str]:
|
|
r = run(f'sc.exe query "{name}"', capture=True)
|
|
if r.returncode != 0:
|
|
return None
|
|
m = _state_re.search(r.stdout or "")
|
|
return m.group(1).upper() if m else None
|
|
|
|
def wait_for_service_state(name: str, target: str, timeout_s: int = 45) -> bool:
|
|
"""Wartet, bis der Dienst den gewünschten Zustand erreicht (z.B. STOPPED)."""
|
|
deadline = time.time() + timeout_s
|
|
target = target.upper()
|
|
while time.time() < deadline:
|
|
st = get_service_state(name)
|
|
if st is None and target == "DELETED":
|
|
return True
|
|
if st == target:
|
|
return True
|
|
time.sleep(1.5)
|
|
return False
|
|
|
|
def stop_service(name: str, timeout_s: int = 45) -> None:
|
|
if not service_exists(name):
|
|
print(f'Dienst nicht vorhanden: {name} (übersprungen)')
|
|
return
|
|
state = get_service_state(name)
|
|
if state == "STOPPED":
|
|
print(f'Dienst bereits gestoppt: {name}')
|
|
else:
|
|
run(f'sc.exe stop "{name}"')
|
|
if not wait_for_service_state(name, "STOPPED", timeout_s):
|
|
print(f'⚠️ Timeout beim Stoppen von {name} (fahre fort)')
|
|
|
|
def delete_service(name: str, timeout_s: int = 30) -> None:
|
|
if not service_exists(name):
|
|
print(f'Dienst nicht vorhanden: {name} (übersprungen)')
|
|
return
|
|
run(f'sc.exe delete "{name}"')
|
|
# Warten, bis sc query fehlschlägt -> gilt als gelöscht
|
|
deadline = time.time() + timeout_s
|
|
while time.time() < deadline:
|
|
if not service_exists(name):
|
|
print(f'Dienst gelöscht: {name}')
|
|
return
|
|
time.sleep(1.5)
|
|
print(f'⚠️ Timeout beim Löschen von {name} (sc query liefert weiterhin Erfolg)')
|
|
|
|
def stop_and_delete_service(name: str) -> None:
|
|
stop_service(name)
|
|
delete_service(name)
|
|
|
|
# ----------------------------- Filesystem -----------------------------
|
|
|
|
def _on_rm_error(func, path, exc_info):
|
|
try:
|
|
os.chmod(path, 0o700)
|
|
func(path)
|
|
except Exception:
|
|
pass
|
|
|
|
def remove_dir(path: Path) -> None:
|
|
"""Löscht rekursiv ein Verzeichnis, falls vorhanden (mit Retry bei Sperren)."""
|
|
if not path.exists():
|
|
print(f"Verzeichnis nicht gefunden (übersprungen): {path}")
|
|
return
|
|
for attempt in range(3):
|
|
try:
|
|
shutil.rmtree(path, onerror=_on_rm_error)
|
|
print(f"Verzeichnis entfernt: {path}")
|
|
return
|
|
except Exception as e:
|
|
print(f"Fehler beim Entfernen von {path} (Versuch {attempt+1}/3): {e}")
|
|
time.sleep(1.5)
|
|
print(f"⚠️ Konnte Verzeichnis nicht entfernen: {path}")
|
|
|
|
# ----------------------------- Main -----------------------------
|
|
|
|
def main() -> None:
|
|
ensure_admin()
|
|
|
|
# 1) Prozesse beenden (best effort)
|
|
stop_process("influxd")
|
|
stop_process("serial_to_influxdb")
|
|
|
|
# 2) Dienste in richtiger Reihenfolge entfernen
|
|
# Hinweis: laut Vorgabe hängt InfluxDBmDNS von InfluxDB2 ab,
|
|
# deshalb zuerst mDNS entfernen, dann InfluxDB2.
|
|
stop_and_delete_service("InfluxDBmDNS")
|
|
# Warten, damit abhängige Aufräumarbeiten von mDNS fertig sind
|
|
time.sleep(2.0)
|
|
|
|
stop_and_delete_service("InfluxDB2")
|
|
|
|
# Optional: euer eigener Dienst, falls vorhanden
|
|
stop_and_delete_service("SerialToInfluxService")
|
|
|
|
# 3) Verzeichnisse löschen
|
|
# - Systemprofile: C:\Windows\System32\config\systemprofile\.influxdbv2
|
|
# - Benutzerprofil: C:\Users\%USER%\.influxdbv2
|
|
# - Program Files: C:\Program Files\InfluxDB2
|
|
# - ProgramData: C:\ProgramData\InfluxDB2
|
|
systemprofile_influx = Path(r"C:\Windows\System32\config\systemprofile\.influxdbv2")
|
|
user_influx = Path(os.path.expandvars(r"%USERPROFILE%")) / ".influxdbv2"
|
|
|
|
program_files = Path(os.environ.get("ProgramFiles", r"C:\Program Files"))
|
|
pf_influx = program_files / "InfluxDB2"
|
|
|
|
# (Optional) Falls jemand in PF(x86) installiert hat:
|
|
program_files_x86 = Path(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"))
|
|
pf86_influx = program_files_x86 / "InfluxDB2"
|
|
|
|
# NEU: ProgramData-Ordner
|
|
program_data = Path(os.environ.get("ProgramData", r"C:\ProgramData"))
|
|
pd_influx = program_data / "InfluxDB2"
|
|
|
|
for p in [systemprofile_influx, user_influx, pf_influx, pf86_influx, pd_influx]:
|
|
remove_dir(p)
|
|
|
|
# Abschlussmeldung
|
|
msg = "Alle Komponenten wurden (bestmöglich) deinstalliert."
|
|
print(msg)
|
|
try:
|
|
ctypes.windll.user32.MessageBoxW(None, msg, "Deinstallation abgeschlossen", 0x40)
|
|
except Exception:
|
|
pass
|
|
|
|
if __name__ == "__main__":
|
|
main()
|