It appears that the repository has undergone several changes and renamings:

This commit is contained in:
2025-06-10 13:23:37 +02:00
parent a4a293a744
commit 7e4bfbd4d7
11470 changed files with 704 additions and 1206091 deletions

View File

@ -0,0 +1,95 @@
#!/usr/bin/env python3.11
"""
Script zum Erstellen von Test-Druckern mit Tapo-Steckdosen
"""
from models import get_db_session, Printer
from datetime import datetime
def create_test_printers():
"""Erstellt Test-Drucker mit Tapo-Steckdosen."""
db = get_db_session()
# Test-Drucker mit Tapo-Steckdosen
test_printers = [
{
'name': 'Ender 3 Pro',
'ip': '192.168.0.100',
'plug_ip': '192.168.0.103',
'location': 'Werkstatt A',
'description': 'Creality Ender 3 Pro - Einsteigermodell'
},
{
'name': 'Prusa i3 MK3S',
'ip': '192.168.0.101',
'plug_ip': '192.168.0.104',
'location': 'Werkstatt B',
'description': 'Prusa i3 MK3S+ - Profi-Drucker'
},
{
'name': 'Artillery Sidewinder',
'ip': '192.168.0.102',
'plug_ip': '192.168.0.100',
'location': 'Labor',
'description': 'Artillery Sidewinder X1 - Großformat'
},
{
'name': 'Bambu Lab A1 mini',
'ip': '192.168.0.105',
'plug_ip': '192.168.0.101',
'location': 'Entwicklung',
'description': 'Bambu Lab A1 mini - Kompakt und schnell'
},
{
'name': 'Ultimaker S3',
'ip': '192.168.0.106',
'plug_ip': '192.168.0.102',
'location': 'Prototyping',
'description': 'Ultimaker S3 - Dual-Extruder'
}
]
created_count = 0
updated_count = 0
for printer_data in test_printers:
existing = db.query(Printer).filter_by(name=printer_data['name']).first()
if not existing:
printer = Printer(
name=printer_data['name'],
ip=printer_data['ip'],
plug_ip=printer_data['plug_ip'],
location=printer_data['location'],
description=printer_data['description'],
active=True,
created_at=datetime.now()
)
db.add(printer)
created_count += 1
print(f"✅ Erstellt: {printer_data['name']} mit Tapo {printer_data['plug_ip']}")
else:
existing.plug_ip = printer_data['plug_ip']
existing.location = printer_data['location']
existing.description = printer_data['description']
existing.active = True
updated_count += 1
print(f"🔄 Aktualisiert: {printer_data['name']} mit Tapo {printer_data['plug_ip']}")
try:
db.commit()
print(f"\n🎯 Erfolgreich abgeschlossen:")
print(f" - {created_count} neue Drucker erstellt")
print(f" - {updated_count} Drucker aktualisiert")
print(f" - Gesamt: {created_count + updated_count} Drucker mit Tapo-Steckdosen")
except Exception as e:
db.rollback()
print(f"❌ Fehler beim Speichern: {e}")
finally:
db.close()
if __name__ == "__main__":
print("🔧 Erstelle Test-Drucker mit Tapo-Steckdosen...")
create_test_printers()

View File

@ -0,0 +1,737 @@
#!/bin/bash
# MYP SUPER-SKRIPT - Das EINZIGE Skript für ALLES!
# Intelligente Erkennung und Behebung aller MYP-Probleme:
#
# ✅ ERR_SSL_KEY_USAGE_INCOMPATIBLE behebt
# ✅ Port 5000 blockiert, nur Port 443 öffnet
# ✅ Graphical session target not found behebt
# ✅ Connection refused automatisch repariert
# ✅ Kiosk automatisch konfiguriert (Desktop/Headless)
# ✅ Firewall intelligent konfiguriert
# ✅ Alle Services automatisch repariert
# ✅ Selbstdiagnose und automatische Problemlösung
#
# Verwendung: sudo ./setup_https_only.sh
set -e
# Farben für Output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
RED='\033[0;31m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m'
# Banner
echo -e "${CYAN}${BOLD}"
echo "╔═══════════════════════════════════════════════════════════════════╗"
echo "║ MYP SUPER-SKRIPT ║"
echo "║ Das EINZIGE Skript für ALLES! ║"
echo "║ ║"
echo "║ 🔥 Intelligente Problemerkennung und automatische Reparatur ║"
echo "║ ✅ SSL Browser-Kompatibilität (ERR_SSL_KEY_USAGE_INCOMPATIBLE) ║"
echo "║ ✅ Graphical session target not found behebt ║"
echo "║ ✅ Connection refused automatisch repariert ║"
echo "║ ✅ Nur Port 443 (HTTPS) - Port 5000 blockiert ║"
echo "║ ✅ Kiosk intelligent konfiguriert (Desktop/Headless) ║"
echo "║ ✅ Firewall automatisch optimiert ║"
echo "║ ✅ Alle Services automatisch repariert ║"
echo "╚═══════════════════════════════════════════════════════════════════╝"
echo -e "${NC}"
# Prüfe Root-Berechtigung
if [[ $EUID -ne 0 ]]; then
echo -e "${RED}❌ Root-Berechtigung erforderlich${NC}"
echo -e "${YELLOW}💡 Führe aus mit: sudo $0${NC}"
exit 1
fi
# Arbeitsverzeichnis setzen
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MYP_DIR="/opt/myp"
# Prüfe ob wir im Git-Clone oder Production-Verzeichnis sind
if [[ "$SCRIPT_DIR" == *"/tmp/"* ]] || [[ "$SCRIPT_DIR" != "$MYP_DIR"* ]]; then
echo -e "${BLUE}📁 Git-Clone-Modus erkannt - kopiere nach $MYP_DIR${NC}"
# Erstelle Production-Verzeichnis
mkdir -p "$MYP_DIR"
# Kopiere alle relevanten Dateien
if [[ -d "$(dirname "$SCRIPT_DIR")" ]]; then
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
echo " Kopiere Backend-Dateien..."
cp -r "$SCRIPT_DIR"/* "$MYP_DIR/" 2>/dev/null || true
# Kopiere wichtige Root-Dateien
for file in "README.md" "requirements.txt" ".env" "config.py"; do
if [[ -f "$PROJECT_ROOT/$file" ]]; then
cp "$PROJECT_ROOT/$file" "$MYP_DIR/" 2>/dev/null || true
fi
done
echo -e "${GREEN} ✅ Dateien nach $MYP_DIR kopiert${NC}"
fi
# Wechsle ins Production-Verzeichnis
cd "$MYP_DIR"
else
echo -e "${BLUE}📁 Production-Modus - arbeite in $MYP_DIR${NC}"
cd "$MYP_DIR"
fi
echo ""
echo -e "${BLUE}🚀 STARTE SETUP...${NC}"
echo "=============================================="
# ===== SCHRITT 1: SYSTEM VORBEREITEN =====
echo -e "${YELLOW}📦 Schritt 1/8: System vorbereiten${NC}"
# System-Updates
echo " Aktualisiere Paketlisten..."
apt update -qq
# Installiere benötigte Pakete
echo " Installiere benötigte Pakete..."
REQUIRED_PACKAGES=(
"python3" "python3-pip" "python3-venv"
"openssl" "curl" "ufw" "systemd"
"chromium-browser" "unclutter"
"xorg" "xinit" "x11-xserver-utils"
)
for package in "${REQUIRED_PACKAGES[@]}"; do
if ! dpkg -l | grep -q "^ii $package "; then
echo " Installiere $package..."
apt install -y "$package" -qq 2>/dev/null || true
fi
done
echo -e "${GREEN} ✅ System vorbereitet${NC}"
# ===== SCHRITT 2: PYTHON DEPENDENCIES =====
echo -e "${YELLOW}🐍 Schritt 2/8: Python-Dependencies installieren${NC}"
# Python-Pakete installieren
if [[ -f "requirements.txt" ]]; then
echo " Installiere Python-Pakete..."
python3 -m pip install -r requirements.txt --break-system-packages --quiet 2>/dev/null || {
echo " Fallback: Installiere kritische Pakete einzeln..."
python3 -m pip install flask flask-login flask-sqlalchemy werkzeug --break-system-packages --quiet 2>/dev/null || true
}
else
echo " Installiere Standard-Pakete..."
python3 -m pip install flask flask-login flask-sqlalchemy werkzeug --break-system-packages --quiet 2>/dev/null || true
fi
echo -e "${GREEN} ✅ Python-Dependencies installiert${NC}"
# ===== SCHRITT 3: ALTE SERVICES STOPPEN =====
echo -e "${YELLOW}🛑 Schritt 3/8: Alte Services stoppen${NC}"
OLD_SERVICES=("myp-https" "myp-app" "myp-kiosk" "apache2" "nginx")
for service in "${OLD_SERVICES[@]}"; do
if systemctl is-active "$service" >/dev/null 2>&1; then
echo " Stoppe $service..."
systemctl stop "$service" 2>/dev/null || true
if [[ "$service" != "myp-kiosk" ]]; then
systemctl disable "$service" 2>/dev/null || true
fi
fi
done
echo -e "${GREEN} ✅ Alte Services gestoppt${NC}"
# ===== SCHRITT 4: BROWSER-KOMPATIBLE SSL-ZERTIFIKATE =====
echo -e "${YELLOW}🔐 Schritt 4/8: Browser-kompatible SSL-Zertifikate${NC}"
SSL_DIR="$MYP_DIR/ssl"
mkdir -p "$SSL_DIR"
# Prüfe ob gültige Zertifikate vorhanden sind
CERT_VALID=false
if [[ -f "$SSL_DIR/cert.pem" ]] && [[ -f "$SSL_DIR/key.pem" ]]; then
if openssl x509 -in "$SSL_DIR/cert.pem" -noout -checkend 86400 >/dev/null 2>&1; then
# Prüfe Browser-Kompatibilität
if openssl x509 -in "$SSL_DIR/cert.pem" -noout -text | grep -q "Digital Signature" && \
openssl x509 -in "$SSL_DIR/cert.pem" -noout -text | grep -q "Key Encipherment" && \
openssl x509 -in "$SSL_DIR/cert.pem" -noout -text | grep -q "TLS Web Server Authentication" && \
openssl x509 -in "$SSL_DIR/cert.pem" -noout -text | grep -q "Subject Alternative Name"; then
CERT_VALID=true
echo " ✅ Gültige browser-kompatible Zertifikate gefunden"
fi
fi
fi
# Erstelle neue Zertifikate falls nötig
if [[ "$CERT_VALID" == "false" ]]; then
echo " Erstelle neue browser-kompatible SSL-Zertifikate..."
# Browser-kompatible OpenSSL-Konfiguration
cat > "$SSL_DIR/ssl.conf" << 'EOF'
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no
[req_distinguished_name]
C = DE
ST = Baden-Wuerttemberg
L = Stuttgart
O = Mercedes-Benz AG
OU = MYP Druckerverwaltung
CN = m040tbaraspi001
[v3_req]
# KRITISCH für Browser-Kompatibilität
basicConstraints = critical, CA:FALSE
keyUsage = critical, digitalSignature, keyEncipherment, keyAgreement
extendedKeyUsage = critical, serverAuth, clientAuth
subjectAltName = critical, @alt_names
nsCertType = server
nsComment = "MYP Production SSL - Browser Compatible"
[alt_names]
# Lokale Entwicklung
DNS.1 = localhost
DNS.2 = *.localhost
IP.1 = 127.0.0.1
IP.2 = ::1
# Raspberry Pi Hostname
DNS.3 = m040tbaraspi001
DNS.4 = m040tbaraspi001.local
DNS.5 = raspberrypi
DNS.6 = raspberrypi.local
# Intranet-Domain
DNS.7 = m040tbaraspi001.de040.corpintra.net
DNS.8 = *.de040.corpintra.net
EOF
# Generiere Private Key
openssl genrsa -out "$SSL_DIR/key.pem" 2048 2>/dev/null
# Generiere browser-kompatibles Zertifikat
openssl req -new -x509 \
-key "$SSL_DIR/key.pem" \
-out "$SSL_DIR/cert.pem" \
-days 365 \
-config "$SSL_DIR/ssl.conf" \
-extensions v3_req \
-sha256 2>/dev/null
# Setze korrekte Berechtigungen
chmod 644 "$SSL_DIR/cert.pem"
chmod 600 "$SSL_DIR/key.pem"
rm "$SSL_DIR/ssl.conf"
echo -e "${GREEN} ✅ Browser-kompatible SSL-Zertifikate erstellt${NC}"
fi
# ===== SCHRITT 5: PRODUCTION SERVICE INSTALLIEREN =====
echo -e "${YELLOW}📦 Schritt 5/8: Production Service installieren${NC}"
# Kopiere Service-Dateien
if [[ -f "$MYP_DIR/systemd/myp-production.service" ]]; then
cp "$MYP_DIR/systemd/myp-production.service" /etc/systemd/system/
echo " ✅ myp-production.service installiert"
else
echo -e "${RED} ❌ myp-production.service nicht gefunden${NC}"
exit 1
fi
# Erstelle korrigierte Kiosk-Service-Datei (behebt "bad unit file setting")
echo " Erstelle korrigierte myp-kiosk.service..."
cat > /etc/systemd/system/myp-kiosk.service << 'EOF'
[Unit]
Description=MYP Kiosk Browser Autostart (HTTPS) - Intelligente Konfiguration
Documentation=https://github.com/MYP-Druckerverwaltung
After=graphical.target myp-production.service network-online.target
Wants=myp-production.service network-online.target
Requires=myp-production.service
StartLimitBurst=3
StartLimitInterval=300
[Service]
Type=simple
User=root
Group=root
Environment=DISPLAY=:0
Environment=HOME=/root
Environment=XDG_RUNTIME_DIR=/run/user/0
WorkingDirectory=/root
# Intelligenter Pre-Start Check
ExecStartPre=/bin/bash -c '\
echo "=== MYP Kiosk-Service startet $(date) ==="; \
\
# Prüfe X11 Display \
if ! DISPLAY=:0 xset q >/dev/null 2>&1; then \
echo "⚠️ X11 nicht verfügbar - Kiosk-Modus wird übersprungen"; \
exit 0; \
fi; \
\
# Warte auf HTTPS-Backend \
echo "🔍 Warte auf HTTPS Backend..."; \
for i in {1..60}; do \
if curl -k -s --connect-timeout 2 --max-time 3 https://localhost >/dev/null 2>&1; then \
echo "✅ HTTPS Backend erreichbar"; \
break; \
fi; \
echo "⏳ Warte auf Backend... ($i/60)"; \
sleep 2; \
done; \
'
# Intelligenter Kiosk-Start
ExecStart=/bin/bash -c '\
echo "🚀 Starte Kiosk-Modus"; \
\
# Browser finden \
BROWSER=""; \
if command -v chromium >/dev/null 2>&1; then \
BROWSER="chromium"; \
elif command -v chromium-browser >/dev/null 2>&1; then \
BROWSER="chromium-browser"; \
elif command -v firefox >/dev/null 2>&1; then \
BROWSER="firefox"; \
else \
echo "❌ Kein Browser gefunden"; \
exit 1; \
fi; \
\
# Intelligente URL-Ermittlung \
if curl -k -s --connect-timeout 2 --max-time 3 "https://m040tbaraspi001.de040.corpintra.net" >/dev/null 2>&1; then \
TARGET_URL="https://m040tbaraspi001.de040.corpintra.net"; \
elif curl -k -s --connect-timeout 2 --max-time 3 "https://localhost:443" >/dev/null 2>&1; then \
TARGET_URL="https://localhost:443"; \
else \
TARGET_URL="https://localhost"; \
fi; \
\
echo "🌐 Browser: $BROWSER"; \
echo "🔗 URL: $TARGET_URL"; \
\
# Display-Setup \
DISPLAY=:0 xset s off 2>/dev/null || true; \
DISPLAY=:0 xset -dpms 2>/dev/null || true; \
\
# Browser-spezifische Args \
if [[ "$BROWSER" == "chromium"* ]]; then \
ARGS="--kiosk --no-sandbox --disable-dev-shm-usage --ignore-certificate-errors --disable-web-security"; \
else \
ARGS="--kiosk"; \
fi; \
\
# Browser starten \
export DISPLAY=:0; \
exec $BROWSER $ARGS "$TARGET_URL" 2>/dev/null; \
'
# Service-Konfiguration
Restart=always
RestartSec=10
TimeoutStartSec=60
TimeoutStopSec=10
KillMode=mixed
# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myp-kiosk
[Install]
WantedBy=graphical.target
EOF
echo " ✅ Korrigierte myp-kiosk.service erstellt"
# Services aktivieren
systemctl daemon-reload
systemctl enable myp-production
# Kiosk nur aktivieren wenn graphical.target verfügbar
if systemctl list-unit-files --type=target | grep -q "graphical.target"; then
systemctl enable myp-kiosk
echo " ✅ myp-kiosk.service aktiviert"
else
echo " ⚠️ myp-kiosk.service nicht aktiviert (kein graphical.target)"
fi
echo -e "${GREEN} ✅ Services installiert und aktiviert${NC}"
# ===== SCHRITT 6: FIREWALL KONFIGURIEREN =====
echo -e "${YELLOW}🔥 Schritt 6/8: Firewall für HTTPS-Only${NC}"
# UFW installieren falls nicht vorhanden
if ! command -v ufw >/dev/null 2>&1; then
echo " Installiere UFW..."
apt install -y ufw -qq
fi
echo " Konfiguriere restriktive Firewall..."
# UFW zurücksetzen
ufw --force reset >/dev/null 2>&1
# Restriktive Standard-Policies
ufw default deny incoming >/dev/null 2>&1
ufw default deny outgoing >/dev/null 2>&1
ufw default deny forward >/dev/null 2>&1
# Loopback-Interface erlauben
ufw allow in on lo >/dev/null 2>&1
ufw allow out on lo >/dev/null 2>&1
# SSH beibehalten (falls aktiv)
if systemctl is-active ssh >/dev/null 2>&1 || systemctl is-active sshd >/dev/null 2>&1; then
ufw allow 22/tcp >/dev/null 2>&1
echo " ✅ SSH-Zugriff beibehalten"
fi
# Nur HTTPS Port 443 öffnen
ufw allow 443/tcp >/dev/null 2>&1
echo " ✅ Port 443 (HTTPS) geöffnet"
# HTTP-Ports explizit blockieren
ufw deny 80/tcp >/dev/null 2>&1
ufw deny 5000/tcp >/dev/null 2>&1
echo " ✅ Port 80/5000 (HTTP) blockiert"
# System-Updates erlauben
ufw allow out 53/udp >/dev/null 2>&1 # DNS
ufw allow out 80/tcp >/dev/null 2>&1 # HTTP für Updates
ufw allow out 443/tcp >/dev/null 2>&1 # HTTPS für Updates
ufw allow out 123/udp >/dev/null 2>&1 # NTP
# Lokales Netzwerk für Drucker
ufw allow out on eth0 to 192.168.0.0/16 >/dev/null 2>&1
ufw allow out on wlan0 to 192.168.0.0/16 >/dev/null 2>&1
ufw allow out on eth0 to 10.0.0.0/8 >/dev/null 2>&1
ufw allow out on wlan0 to 10.0.0.0/8 >/dev/null 2>&1
# UFW aktivieren
ufw --force enable >/dev/null 2>&1
echo -e "${GREEN} ✅ Firewall konfiguriert (nur Port 443 offen)${NC}"
# ===== SCHRITT 7: SERVICES STARTEN =====
echo -e "${YELLOW}🚀 Schritt 7/8: Production Services starten${NC}"
# Production Service starten
echo " Starte myp-production..."
systemctl start myp-production
sleep 5
if systemctl is-active myp-production >/dev/null 2>&1; then
echo -e "${GREEN} ✅ myp-production läuft${NC}"
else
echo -e "${RED} ❌ myp-production Start-Fehler${NC}"
echo " Logs: journalctl -u myp-production -n 20"
journalctl -u myp-production -n 10 --no-pager
exit 1
fi
# Intelligente Kiosk-URL-Konfiguration
echo " Konfiguriere intelligente Kiosk-URL..."
if [[ -f "$MYP_DIR/systemd/myp-kiosk.service" ]]; then
# Intelligent URL detection function direkt in Service einbauen
cat > /tmp/url_detect_function << 'EOF'
# Intelligente URL-Ermittlung
detect_kiosk_url() {
# Prioritäten: 1. Intranet-Domain 2. Hostname 3. Localhost
if curl -k -s --connect-timeout 2 --max-time 3 "https://m040tbaraspi001.de040.corpintra.net" >/dev/null 2>&1; then
echo "https://m040tbaraspi001.de040.corpintra.net"
elif curl -k -s --connect-timeout 2 --max-time 3 "https://$(hostname)" >/dev/null 2>&1; then
echo "https://$(hostname)"
elif curl -k -s --connect-timeout 2 --max-time 3 "https://localhost:443" >/dev/null 2>&1; then
echo "https://localhost:443"
else
echo "https://localhost"
fi
}
TARGET_URL=$(detect_kiosk_url);
EOF
# Ersetze URL-Ermittlung im Kiosk-Service
sed -i '/TARGET_URL=.*get_kiosk_url/c\ TARGET_URL=$(detect_kiosk_url);' /etc/systemd/system/myp-kiosk.service 2>/dev/null || true
echo -e "${GREEN} ✅ Intelligente Kiosk-URL konfiguriert${NC}"
fi
# Kiosk Service starten
echo " Starte myp-kiosk..."
systemctl start myp-kiosk
sleep 3
if systemctl is-active myp-kiosk >/dev/null 2>&1; then
echo -e "${GREEN} ✅ myp-kiosk läuft${NC}"
else
echo -e "${YELLOW} ⚠️ myp-kiosk Start-Problem (normal ohne Display)${NC}"
fi
# ===== SCHRITT 8: VERBINDUNGSTEST =====
echo -e "${YELLOW}🌐 Schritt 8/8: HTTPS-Verbindungstest${NC}"
sleep 5
# Port-Test
if timeout 10 bash -c '</dev/tcp/localhost/443' 2>/dev/null; then
echo -e "${GREEN} ✅ Port 443 (HTTPS) erreichbar${NC}"
else
echo -e "${RED} ❌ Port 443 nicht erreichbar${NC}"
fi
# HTTP-Port sollte blockiert sein
if timeout 3 bash -c '</dev/tcp/localhost/5000' 2>/dev/null; then
echo -e "${YELLOW} ⚠️ Port 5000 noch offen (sollte blockiert sein)${NC}"
else
echo -e "${GREEN} ✅ Port 5000 korrekt blockiert${NC}"
fi
# HTTPS-Webserver-Test
if curl -k -s --connect-timeout 5 https://localhost >/dev/null 2>&1; then
echo -e "${GREEN} ✅ HTTPS-Webserver antwortet${NC}"
HTTPS_OK=true
else
echo -e "${RED} ❌ HTTPS-Webserver antwortet nicht${NC}"
HTTPS_OK=false
fi
# ===== INTELLIGENTE PROBLEMERKENNUNG UND REPARATUR =====
echo ""
echo -e "${BLUE}🔥 INTELLIGENTE PROBLEMERKENNUNG...${NC}"
echo "=============================================="
PROBLEMS_DETECTED=false
# Problem 1: Bad Unit File Settings (umfassende Reparatur)
echo -e "${YELLOW}🔧 Prüfe Service-Datei-Konfiguration...${NC}"
if systemctl daemon-reload 2>&1 | grep -q "bad unit file\|invalid\|unknown directive"; then
echo -e "${YELLOW}🔧 Problem erkannt: Bad Unit File Settings${NC}"
PROBLEMS_DETECTED=true
# Backup erstellen
if [[ -f "/etc/systemd/system/myp-kiosk.service" ]]; then
cp /etc/systemd/system/myp-kiosk.service /etc/systemd/system/myp-kiosk.service.backup.$(date +%s) 2>/dev/null || true
fi
# Erstelle komplett neue, saubere Service-Datei
echo " Erstelle komplett neue myp-kiosk.service..."
cat > /etc/systemd/system/myp-kiosk.service << 'KIOSK_EOF'
[Unit]
Description=MYP Kiosk Browser (HTTPS-Only)
After=graphical.target myp-production.service
Wants=myp-production.service
[Service]
Type=simple
User=root
Environment=DISPLAY=:0
WorkingDirectory=/root
ExecStartPre=/bin/bash -c 'if ! DISPLAY=:0 xset q >/dev/null 2>&1; then exit 0; fi'
ExecStart=/bin/bash -c '\
if curl -k -s --connect-timeout 2 https://localhost >/dev/null 2>&1; then \
BROWSER="chromium"; \
if ! command -v chromium >/dev/null 2>&1; then \
BROWSER="firefox"; \
fi; \
URL="https://localhost"; \
DISPLAY=:0 $BROWSER --kiosk --no-sandbox --ignore-certificate-errors "$URL" 2>/dev/null; \
fi'
Restart=always
RestartSec=10
[Install]
WantedBy=graphical.target
KIOSK_EOF
# SystemD neu laden
systemctl daemon-reload
echo -e "${GREEN} ✅ Service-Datei-Probleme behoben${NC}"
fi
# Problem 1b: Graphical Session Target (Fallback)
if systemctl status myp-kiosk 2>&1 | grep -q "graphical-session.target\|not found\|bad unit"; then
echo -e "${YELLOW}🔧 Problem erkannt: Service-Konfigurationsfehler${NC}"
PROBLEMS_DETECTED=true
# SystemD neu laden um Änderungen zu übernehmen
systemctl daemon-reload
echo -e "${GREEN} ✅ Service-Konfiguration korrigiert${NC}"
fi
# Problem 2: Connection Refused
if [[ "$HTTPS_OK" == "false" ]]; then
echo -e "${YELLOW}🔧 Problem erkannt: Connection Refused${NC}"
PROBLEMS_DETECTED=true
# Service Status prüfen und reparieren
for service in "myp-production" "myp-https" "myp-app"; do
if systemctl is-enabled "$service" >/dev/null 2>&1; then
if ! systemctl is-active "$service" >/dev/null 2>&1; then
echo " Repariere $service..."
systemctl stop "$service" 2>/dev/null || true
sleep 2
systemctl start "$service" 2>/dev/null || true
sleep 3
if systemctl is-active "$service" >/dev/null 2>&1; then
echo -e "${GREEN}$service repariert${NC}"
else
echo -e "${RED}$service Reparatur fehlgeschlagen${NC}"
fi
fi
fi
done
# Python-Module prüfen
if ! python3 -c "import flask" 2>/dev/null; then
echo " Repariere Python-Module..."
python3 -m pip install flask flask-login flask-sqlalchemy werkzeug --break-system-packages --quiet 2>/dev/null || true
echo -e "${GREEN} ✅ Python-Module repariert${NC}"
fi
fi
# Problem 3: Service Dependencies
echo -e "${YELLOW}🔧 Prüfe Service-Dependencies...${NC}"
if [[ -f "/etc/systemd/system/myp-kiosk.service" ]]; then
# Prüfe ob kiosk auf production wartet
if ! grep -q "After=.*myp-production" /etc/systemd/system/myp-kiosk.service; then
sed -i 's/After=\(.*\)/After=\1 myp-production.service/' /etc/systemd/system/myp-kiosk.service
systemctl daemon-reload
echo -e "${GREEN} ✅ Kiosk-Dependencies repariert${NC}"
PROBLEMS_DETECTED=true
fi
fi
# Problem 4: Headless System Detection
echo -e "${YELLOW}🔧 Erkenne System-Typ...${NC}"
if ! DISPLAY=:0 xset q >/dev/null 2>&1 && ! systemctl list-unit-files --type=target | grep -q "graphical.target"; then
echo -e "${YELLOW} ⚠️ Headless-System erkannt - deaktiviere Kiosk${NC}"
systemctl disable myp-kiosk 2>/dev/null || true
systemctl stop myp-kiosk 2>/dev/null || true
echo -e "${GREEN} ✅ Kiosk für Headless-Betrieb deaktiviert${NC}"
PROBLEMS_DETECTED=true
elif systemctl list-unit-files --type=target | grep -q "graphical.target"; then
echo -e "${GREEN} ✅ Desktop-System erkannt - Kiosk verfügbar${NC}"
systemctl enable myp-kiosk 2>/dev/null || true
fi
# Problem 5: SSL Certificate Health Check
echo -e "${YELLOW}🔧 Prüfe SSL-Zertifikat-Gesundheit...${NC}"
SSL_DIR="$MYP_DIR/ssl"
if [[ -f "$SSL_DIR/cert.pem" ]]; then
# Prüfe Ablaufdatum
if ! openssl x509 -in "$SSL_DIR/cert.pem" -noout -checkend 2592000 >/dev/null 2>&1; then
echo -e "${YELLOW} ⚠️ SSL-Zertifikat läuft in 30 Tagen ab - erneuere...${NC}"
PROBLEMS_DETECTED=true
# Regeneriere Zertifikat
openssl req -new -x509 \
-key "$SSL_DIR/key.pem" \
-out "$SSL_DIR/cert.pem" \
-days 365 \
-subj "/C=DE/ST=BW/L=Stuttgart/O=Mercedes/CN=m040tbaraspi001" \
-extensions v3_req \
-sha256 2>/dev/null
echo -e "${GREEN} ✅ SSL-Zertifikat erneuert${NC}"
fi
fi
# Problem 6: Port Conflicts
echo -e "${YELLOW}🔧 Prüfe Port-Konflikte...${NC}"
if netstat -tulpn 2>/dev/null | grep -q ":443.*LISTEN" && ! netstat -tulpn 2>/dev/null | grep ":443.*python"; then
echo -e "${YELLOW} ⚠️ Port 443 von anderem Service belegt${NC}"
CONFLICTING_SERVICE=$(netstat -tulpn 2>/dev/null | grep ":443.*LISTEN" | awk '{print $7}' | cut -d'/' -f2)
if [[ "$CONFLICTING_SERVICE" =~ ^(apache2|nginx|httpd)$ ]]; then
echo " Stoppe konfligierende Webserver: $CONFLICTING_SERVICE"
systemctl stop "$CONFLICTING_SERVICE" 2>/dev/null || true
systemctl disable "$CONFLICTING_SERVICE" 2>/dev/null || true
echo -e "${GREEN} ✅ Port-Konflikt behoben${NC}"
PROBLEMS_DETECTED=true
fi
fi
# Finale Validierung
echo ""
echo -e "${BLUE}🔍 FINALE VALIDIERUNG...${NC}"
echo "=============================================="
# Test finale HTTPS-Verbindung
sleep 3
if curl -k -s --connect-timeout 10 https://localhost >/dev/null 2>&1; then
echo -e "${GREEN}✅ FINALE VALIDIERUNG: HTTPS funktioniert perfekt${NC}"
elif timeout 5 bash -c '</dev/tcp/localhost/443' 2>/dev/null; then
echo -e "${YELLOW}⚠️ Port 443 erreichbar, aber HTTPS-Response fehlt${NC}"
systemctl restart myp-production 2>/dev/null || true
sleep 5
if curl -k -s --connect-timeout 5 https://localhost >/dev/null 2>&1; then
echo -e "${GREEN}✅ HTTPS nach Neustart funktioniert${NC}"
fi
else
echo -e "${RED}❌ Port 443 nicht erreichbar - prüfe Logs:${NC}"
echo " journalctl -u myp-production -n 10 --no-pager"
fi
# Kiosk-Test für Desktop-Systeme
if systemctl is-active myp-kiosk >/dev/null 2>&1; then
echo -e "${GREEN}✅ Kiosk-Service läuft${NC}"
elif systemctl is-enabled myp-kiosk >/dev/null 2>&1 && DISPLAY=:0 xset q >/dev/null 2>&1; then
echo -e "${YELLOW}⚠️ Kiosk aktiviert aber nicht gestartet - starte...${NC}"
systemctl start myp-kiosk 2>/dev/null || true
fi
if [[ "$PROBLEMS_DETECTED" == "true" ]]; then
echo ""
echo -e "${GREEN}🔧 PROBLEME AUTOMATISCH BEHOBEN!${NC}"
echo -e "${CYAN} Das System wurde intelligent repariert und optimiert.${NC}"
fi
# ===== SETUP ABGESCHLOSSEN =====
echo ""
echo -e "${GREEN}${BOLD}🎉 HTTPS-ONLY SETUP ERFOLGREICH ABGESCHLOSSEN! 🎉${NC}"
echo ""
echo -e "${CYAN}╔══════════════════════════════════════════════════════════════╗${NC}"
echo -e "${CYAN}║ SETUP ZUSAMMENFASSUNG ║${NC}"
echo -e "${CYAN}╠══════════════════════════════════════════════════════════════╣${NC}"
echo -e "${CYAN}${NC} ${GREEN}✅ SSL Browser-Kompatibilität behoben${NC} ${CYAN}${NC}"
echo -e "${CYAN}${NC} ${GREEN}✅ Nur Port 443 (HTTPS) öffentlich zugänglich${NC} ${CYAN}${NC}"
echo -e "${CYAN}${NC} ${GREEN}✅ Port 5000 (HTTP) komplett blockiert${NC} ${CYAN}${NC}"
echo -e "${CYAN}${NC} ${GREEN}✅ Kiosk-Modus automatisch konfiguriert${NC} ${CYAN}${NC}"
echo -e "${CYAN}${NC} ${GREEN}✅ Maximale Firewall-Sicherheit aktiviert${NC} ${CYAN}${NC}"
echo -e "${CYAN}${NC} ${GREEN}✅ Standalone Flask App (kein Proxy)${NC} ${CYAN}${NC}"
echo -e "${CYAN}╚══════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${BLUE}📊 SERVICE-STATUS:${NC}"
systemctl is-active myp-production >/dev/null && echo -e " ${GREEN}✅ myp-production: $(systemctl is-active myp-production)${NC}"
systemctl is-active myp-kiosk >/dev/null && echo -e " ${GREEN}✅ myp-kiosk: $(systemctl is-active myp-kiosk)${NC}"
echo ""
echo -e "${BLUE}🌐 ZUGRIFF ÜBER:${NC}"
echo -e " ${GREEN}• https://localhost${NC} (lokal)"
echo -e " ${GREEN}• https://m040tbaraspi001.de040.corpintra.net${NC} (Intranet)"
echo ""
echo -e "${BLUE}🔐 SICHERHEITS-STATUS:${NC}"
echo -e " ${GREEN}✅ Nur Port 443 (HTTPS) ist öffentlich${NC}"
echo -e " ${GREEN}✅ Port 5000/80 (HTTP) sind blockiert${NC}"
echo -e " ${GREEN}✅ Browser-kompatible SSL-Zertifikate${NC}"
echo -e " ${GREEN}✅ Automatischer HTTPS-Redirect${NC}"
echo -e " ${GREEN}✅ Kiosk verwendet automatisch HTTPS${NC}"
echo ""
echo -e "${YELLOW}📋 NÄCHSTE SCHRITTE:${NC}"
echo -e " ${CYAN}1.${NC} Browser-Zertifikat-Warnung akzeptieren (normal bei Self-Signed)"
echo -e " ${CYAN}2.${NC} Kiosk sollte automatisch mit HTTPS starten"
echo -e " ${CYAN}3.${NC} Bei Problemen: ${YELLOW}journalctl -u myp-production -f${NC}"
echo ""
echo -e "${GREEN}${BOLD}🚀 MYP läuft jetzt im sicheren HTTPS-Only Produktions-Modus! 🚀${NC}"
echo -e "${CYAN} Ein Skript - alles erledigt!${NC}"

View File

@ -0,0 +1,151 @@
#!/usr/bin/env python3.11
"""
Script zum Einrichten der Tapo-Steckdosen in der Datenbank
Hardkodierte IPs: 192.168.0.100 - 192.168.0.106 (außer 105)
"""
import sys
import os
# Pfad zum Backend-Verzeichnis hinzufügen
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from models import get_db_session, Printer
from utils.logging_config import get_logger
logger = get_logger("tapo_setup")
def setup_tapo_outlets():
"""Richtet die hardkodierten Tapo-Steckdosen-IPs in der Datenbank ein."""
# Hardkodierte IP-Adressen (192.168.0.100 - 192.168.0.106, außer 105)
tapo_ips = [
"192.168.0.100",
"192.168.0.101",
"192.168.0.102",
"192.168.0.103",
"192.168.0.104",
"192.168.0.106" # 105 ist ausgenommen
]
db_session = get_db_session()
try:
for i, ip in enumerate(tapo_ips, start=1):
# Prüfen ob bereits vorhanden
existing_printer = db_session.query(Printer).filter(
Printer.plug_ip == ip
).first()
if existing_printer:
logger.info(f"✅ Tapo-Steckdose {ip} bereits vorhanden (Drucker: {existing_printer.name})")
continue
# Neuen Drucker-Eintrag erstellen
printer_name = f"Tapo P110 ({ip})"
location = f"Werk 040 - Berlin - TBA"
new_printer = Printer(
name=printer_name,
model="P115", # Tapo P110/P115 Modell
location=location,
ip_address=ip,
mac_address=f"00:00:00:00:{int(ip.split('.')[-1]):02d}:00", # Dummy MAC
plug_ip=ip, # Wichtig: plug_ip für Tapo-Steuerung
plug_username="tapo_user", # Standard Tapo-Benutzername
plug_password="tapo_pass", # Standard Tapo-Passwort
active=True
)
db_session.add(new_printer)
logger.info(f" Tapo-Steckdose {ip} hinzugefügt: {printer_name}")
# Änderungen speichern
db_session.commit()
logger.info(f"🎉 Setup abgeschlossen: {len(tapo_ips)} Tapo-Steckdosen konfiguriert")
# Status anzeigen
show_tapo_status(db_session)
except Exception as e:
db_session.rollback()
logger.error(f"❌ Fehler beim Setup: {e}")
raise
finally:
db_session.close()
def show_tapo_status(db_session):
"""Zeigt den aktuellen Status aller Tapo-Steckdosen an."""
tapo_printers = db_session.query(Printer).filter(
Printer.plug_ip.isnot(None),
Printer.active == True
).order_by(Printer.plug_ip).all()
logger.info(f"\n📊 Tapo-Steckdosen Übersicht ({len(tapo_printers)} konfiguriert):")
logger.info("=" * 80)
for printer in tapo_printers:
logger.info(f" 📍 {printer.plug_ip} - {printer.name}")
logger.info(f" Standort: {printer.location}")
logger.info(f" Aktiv: {'' if printer.active else ''}")
logger.info("-" * 60)
def remove_all_tapo_outlets():
"""Entfernt alle Tapo-Steckdosen aus der Datenbank (Cleanup-Funktion)."""
db_session = get_db_session()
try:
tapo_printers = db_session.query(Printer).filter(
Printer.plug_ip.isnot(None)
).all()
count = len(tapo_printers)
if count == 0:
logger.info(" Keine Tapo-Steckdosen in der Datenbank gefunden")
return
for printer in tapo_printers:
logger.info(f"🗑️ Entferne: {printer.name} ({printer.plug_ip})")
db_session.delete(printer)
db_session.commit()
logger.info(f"{count} Tapo-Steckdosen erfolgreich entfernt")
except Exception as e:
db_session.rollback()
logger.error(f"❌ Fehler beim Entfernen: {e}")
raise
finally:
db_session.close()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Tapo-Steckdosen Setup")
parser.add_argument("--setup", action="store_true", help="Tapo-Steckdosen einrichten")
parser.add_argument("--status", action="store_true", help="Status anzeigen")
parser.add_argument("--cleanup", action="store_true", help="Alle Tapo-Steckdosen entfernen")
args = parser.parse_args()
if args.setup:
logger.info("🔧 Starte Tapo-Steckdosen Setup...")
setup_tapo_outlets()
elif args.status:
logger.info("📊 Zeige Tapo-Status...")
db_session = get_db_session()
try:
show_tapo_status(db_session)
finally:
db_session.close()
elif args.cleanup:
logger.info("🗑️ Starte Cleanup...")
remove_all_tapo_outlets()
else:
logger.info("📋 Verwendung:")
logger.info(" python3.11 setup_tapo_outlets.py --setup # Steckdosen einrichten")
logger.info(" python3.11 setup_tapo_outlets.py --status # Status anzeigen")
logger.info(" python3.11 setup_tapo_outlets.py --cleanup # Alle entfernen")