#!/usr/bin/env python3 """Prüft die *live* erreichbare Website: Status, Canonicals, JSON-LD, Header, Redirects, robots.txt/Sitemap und die DNS-Reputation (DMARC, SPF, CAA, DNSSEC). Ergänzt scripts/check.py: das prüft den Build, dieses Skript die Realität draußen. Netzwerk und `dig` nötig. Aufruf: python3 scripts/audit.py # Übersicht mit ✓/⚠/✗ python3 scripts/audit.py --strict # Warnungen zählen als Fehler Exit-Code 1, wenn Fehler gefunden wurden. Hintergrund und was zu tun ist: docs/seo-und-reputation.md """ from __future__ import annotations import json import re import subprocess import sys import urllib.error import urllib.request BASE = "https://sonjasrasselbande.de" HOST = "sonjasrasselbande.de" UA = "Mozilla/5.0 (compatible; sonjasrasselbande-audit)" ok_count = 0 warnings: list[str] = [] errors: list[str] = [] def ok(msg: str) -> None: global ok_count ok_count += 1 print(f" ✓ {msg}") def warn(msg: str) -> None: warnings.append(msg) print(f" ⚠ {msg}") def fail(msg: str) -> None: errors.append(msg) print(f" ✗ {msg}") def request(url: str, method: str = "GET") -> tuple[int, dict, str]: """Holt eine URL ohne automatischer Redirect-Folge.""" req = urllib.request.Request(url, headers={"User-Agent": UA}, method=method) opener = urllib.request.build_opener(NoRedirect) try: with opener.open(req, timeout=25) as res: body = res.read().decode("utf-8", "replace") if method == "GET" else "" return res.status, dict(res.headers), body except urllib.error.HTTPError as exc: body = exc.read().decode("utf-8", "replace") if method == "GET" else "" return exc.code, dict(exc.headers), body except Exception as exc: # Netzfehler fail(f"{url} nicht erreichbar: {exc}") return 0, {}, "" class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401 return None def dig(name: str, rtype: str) -> list[str]: try: out = subprocess.run( ["dig", "+short", name, rtype], capture_output=True, text=True, timeout=15, check=False ).stdout except (OSError, subprocess.SubprocessError): return [] return [line.strip().strip('"') for line in out.splitlines() if line.strip()] print(f"\n▶ Erreichbarkeit & Redirects ({HOST})") status, headers, _ = request(f"{BASE}/") if status == 200: ok("Startseite: HTTP 200") else: fail(f"Startseite: HTTP {status}") status, headers, _ = request(f"http://{HOST}/") if status in (301, 308) and str(headers.get("Location", "")).startswith("https://"): ok("http → https: 301") else: fail(f"http → https fehlt (HTTP {status})") status, headers, _ = request(f"https://www.{HOST}/") location = str(headers.get("Location", "")) if status in (301, 308) and "www." not in location: ok("www → ohne www: 301") else: fail(f"www-Redirect fehlt (HTTP {status}, Location: {location or '—'})") status, headers, _ = request(f"{BASE}/kontakt/") if status in (301, 308) and str(headers.get("Location", "")).rstrip("/").endswith("/kontakt"): ok("Trailing Slash: 301 auf kanonische URL") else: fail(f"Trailing Slash wird nicht umgeleitet (HTTP {status})") status, _, _ = request(f"{BASE}/diese-seite-gibt-es-nicht") if status == 404: ok("Unbekannte URL: echter 404") else: fail(f"Unbekannte URL liefert HTTP {status} statt 404") print("\n▶ Seiten aus der Sitemap") sitemap_status, sitemap_headers, sitemap = request(f"{BASE}/sitemap.xml") if sitemap_status == 200 and "xml" in str(sitemap_headers.get("Content-Type", "")): ok("sitemap.xml erreichbar (application/xml)") else: fail(f"sitemap.xml: HTTP {sitemap_status}") urls = re.findall(r"(.*?)", sitemap) if urls: ok(f"{len(urls)} URL(s) in der Sitemap") else: fail("Sitemap enthält keine -Einträge") for url in urls: status, _, html = request(url) path = url.replace(BASE, "") or "/" if status != 200: fail(f"{path}: HTTP {status}") continue problems = [] canonical = re.search(r'rel="canonical" href="([^"]*)"', html) if not canonical or canonical.group(1) != url: problems.append(f"canonical={canonical.group(1) if canonical else '—'}") robots = re.search(r'name="robots" content="([^"]*)"', html) if robots and "noindex" in robots.group(1): problems.append("noindex") if not re.search(r"[^<]{10,78}", html): problems.append("title fehlt oder zu lang (max. ~75 Zeichen)") if html.count("(.*?)', html, re.S): try: json.loads(match.group(1)) except json.JSONDecodeError: problems.append("JSON-LD ungültig") if problems: fail(f"{path}: {', '.join(problems)}") else: ok(f"{path}") print("\n▶ robots.txt") robots_status, _, robots_txt = request(f"{BASE}/robots.txt") if robots_status == 200 and f"Sitemap: {BASE}/sitemap.xml" in robots_txt: ok("robots.txt verweist auf die Sitemap") else: fail("robots.txt fehlt oder ohne Sitemap-Verweis") if re.search(r"^Disallow: /\s*$", robots_txt, re.M): fail("robots.txt sperrt die ganze Seite (Disallow: /)") print("\n▶ Sicherheits-Header (statisch vs. dynamisch)") for path in ("/", "/index.html", "/assets/css/style.css"): status, headers, _ = request(f"{BASE}{path}") lowered = {k.lower(): v for k, v in headers.items()} missing = [h for h in ("strict-transport-security", "x-content-type-options") if h not in lowered] if not missing: ok(f"{path}: HSTS + nosniff vorhanden") else: warn(f"{path}: Header fehlen ({', '.join(missing)}) – netcup-nginx liefert statische Dateien am Apache vorbei") status, headers, _ = request(f"{BASE}/gibtsnicht") lowered = {k.lower(): v for k, v in headers.items()} if "strict-transport-security" in lowered: ok("Fehlerseite (über Apache): HSTS vorhanden") print("\n▶ IndexNow") key = "" try: build_src = open("scripts/build.py", encoding="utf-8").read() match = re.search(r'^INDEXNOW_KEY = "([^"]+)"', build_src, re.M) key = match.group(1) if match else "" except OSError: pass if not key: warn("INDEXNOW_KEY ist in scripts/build.py nicht gesetzt – Bing erfährt nichts von Änderungen") else: status, _, body = request(f"{BASE}/{key}.txt") if status == 200 and body.strip() == key: ok(f"Key-Datei erreichbar ({key}.txt)") else: fail(f"Key-Datei {key}.txt fehlt oder hat falschen Inhalt (HTTP {status})") print("\n▶ DNS-Reputation") dmarc = [r for r in dig(f"_dmarc.{HOST}", "TXT") if r.startswith("v=DMARC1")] if dmarc: policy = re.search(r"\bp=(\w+)", dmarc[0]) pol = policy.group(1) if policy else "?" if pol == "none": warn(f"DMARC vorhanden, aber p=none – später auf quarantine/reject erhöhen") else: ok(f"DMARC aktiv (p={pol})") else: fail("kein DMARC-Record (_dmarc) – häufigster Grund für „unsichere Domain“-Warnungen") spf = [r for r in dig(HOST, "TXT") if r.startswith("v=spf1")] if not spf: fail("kein SPF-Record") elif spf[0].rstrip().endswith("-all"): ok("SPF mit -all (Hardfail)") elif "~all" in spf[0]: warn("SPF endet auf ~all (Softfail) – auf -all umstellen, sobald DMARC-Berichte sauber sind") else: warn(f"SPF ohne eindeutige Policy: {spf[0][:60]}") caa = dig(HOST, "CAA") if caa: ok(f"CAA gesetzt ({len(caa)} Record(s))") else: warn("kein CAA-Record – nur Let's Encrypt sollte Zertifikate ausstellen dürfen") if dig(HOST, "DS"): ok("DNSSEC aktiv (DS-Record vorhanden)") else: warn("kein DS-Record – DNSSEC im netcup-CCP aktivieren") if dig(HOST, "AAAA"): ok("IPv6 (AAAA) vorhanden") else: warn("kein AAAA-Record") print("\n▶ Suchmaschinen-Sichtbarkeit") warn("Index-Status nicht automatisch prüfbar – in der Search Console unter „Seiten“ nachsehen") print(f"\n{ok_count} Prüfung(en) bestanden, {len(warnings)} Hinweis(e), {len(errors)} Fehler") if warnings: print("\nHinweise:") for w in warnings: print(f" ⚠ {w}") if errors: print("\nFehler:") for e in errors: print(f" ✗ {e}") strict = "--strict" in sys.argv return_code = 1 if errors or (strict and warnings) else 0 sys.exit(return_code)