Pythonskripte für mDNS und uninstall hinzugefügt
This commit is contained in:
Executable
+76
@@ -0,0 +1,76 @@
|
||||
# announce.py
|
||||
from zeroconf import ServiceInfo, Zeroconf
|
||||
import socket
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import signal
|
||||
|
||||
SERVICE_TYPE = "_influxdb2._tcp.local."
|
||||
PORT = 8086
|
||||
|
||||
# ---------------- helpers ----------------
|
||||
def get_lan_ip() -> str:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
try:
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip = s.getsockname()[0]
|
||||
finally:
|
||||
s.close()
|
||||
return ip
|
||||
|
||||
def mdns_safe_hostname(name: str) -> str:
|
||||
name = name.strip().lower()
|
||||
name = re.sub(r"[^a-z0-9-]", "-", name)
|
||||
name = re.sub(r"-{2,}", "-", name)
|
||||
name = name.strip("-") or "host"
|
||||
return name
|
||||
|
||||
# ---------------- main ----------------
|
||||
stop = False
|
||||
def handle_signal(sig, frame):
|
||||
global stop
|
||||
stop = True
|
||||
|
||||
def main():
|
||||
raw_host = socket.gethostname()
|
||||
host = mdns_safe_hostname(raw_host)
|
||||
|
||||
try:
|
||||
ip = get_lan_ip()
|
||||
except Exception as e:
|
||||
sys.exit(1)
|
||||
|
||||
server_fqdn = f"{host}.local."
|
||||
instance_name = f"influxdb2-{host}.{SERVICE_TYPE}"
|
||||
|
||||
txt = {"role": "primary", "path": "/", "ver": "1.0.0"}
|
||||
|
||||
info = ServiceInfo(
|
||||
type_=SERVICE_TYPE,
|
||||
name=instance_name,
|
||||
addresses=[socket.inet_aton(ip)],
|
||||
port=PORT,
|
||||
properties=txt,
|
||||
server=server_fqdn,
|
||||
)
|
||||
|
||||
zc = Zeroconf()
|
||||
signal.signal(signal.SIGINT, handle_signal)
|
||||
signal.signal(signal.SIGTERM, handle_signal)
|
||||
|
||||
try:
|
||||
# hier kannst du evtl. in ein Logfile schreiben, statt print
|
||||
print(f"Announce {instance_name} @ {ip}:{PORT}")
|
||||
zc.register_service(info)
|
||||
while not stop:
|
||||
time.sleep(1)
|
||||
finally:
|
||||
try:
|
||||
zc.unregister_service(info)
|
||||
finally:
|
||||
zc.close()
|
||||
print("Zeroconf: beendet.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+34
@@ -0,0 +1,34 @@
|
||||
from zeroconf import Zeroconf, ServiceBrowser
|
||||
|
||||
SERVICE = "_myapp._tcp.local."
|
||||
|
||||
class Listener:
|
||||
def __init__(self, zc: Zeroconf):
|
||||
self.zc = zc
|
||||
|
||||
def add_service(self, zc, type_, name):
|
||||
print("ADD ", name)
|
||||
info = zc.get_service_info(type_, name, timeout=3000)
|
||||
if info:
|
||||
addrs = [ "%d.%d.%d.%d" % tuple(a) for a in info.addresses ]
|
||||
print(" Host: ", info.server)
|
||||
print(" IPs: ", addrs)
|
||||
print(" Port: ", info.port)
|
||||
# TXT-Records
|
||||
props = { k.decode(): v.decode() for k, v in info.properties.items() }
|
||||
print(" TXT: ", props)
|
||||
else:
|
||||
print(" (keine Details auflösbar)")
|
||||
|
||||
def remove_service(self, zc, type_, name):
|
||||
print("REM ", name)
|
||||
|
||||
def update_service(self, zc, type_, name):
|
||||
print("UPD ", name)
|
||||
|
||||
zc = Zeroconf()
|
||||
try:
|
||||
ServiceBrowser(zc, SERVICE, Listener(zc))
|
||||
input("Browsing… Enter zum Beenden\n")
|
||||
finally:
|
||||
zc.close()
|
||||
Executable
+186
@@ -0,0 +1,186 @@
|
||||
#!/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()
|
||||
Reference in New Issue
Block a user