#!/usr/bin/env python3 # -*- coding: utf-8 -*- import subprocess import os import sys import argparse # HINWEIS: Dieses Skript ist für die Ausführung INNERHALB des Containers gedacht. def run_command(command_str, description, input_str=None): """Führt einen Shell-Befehl als String aus und prüft auf Fehler.""" print(f"\n--- {description} ---") try: process = subprocess.run( command_str, check=True, shell=True, text=True, input=input_str, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) print(f"--- ERFOLG: {description} ---") if process.stdout: print(f"STDOUT:\n{process.stdout}") if process.stderr: print(f"STDERR:\n{process.stderr}", file=sys.stderr) except subprocess.CalledProcessError as e: print(f"FEHLER bei '{description}': Befehl '{command_str}' gab den Exit-Code {e.returncode} zurück", file=sys.stderr) if e.stdout: print(f"STDOUT:\n{e.stdout}", file=sys.stderr) if e.stderr: print(f"STDERR:\n{e.stderr}", file=sys.stderr) sys.exit(1) def main(): """Hauptfunktion des Skripts.""" if os.geteuid() != 0: print("FEHLER: Dieses Skript muss als root im Container ausgeführt werden.", file=sys.stderr) sys.exit(1) parser = argparse.ArgumentParser(description="Konfiguriert einen neuen Container.") parser.add_argument("password", help="Das gewünschte root-Passwort.") parser.add_argument("hostname", help="Der Hostname für diesen Container.") parser.add_argument("distro", help="Die Distribution des Containers (z.B. 'arch', 'ubuntu').") args = parser.parse_args() root_password = args.password hostname = args.hostname distro = args.distro password_input = f"{root_password}\n{root_password}\n" # --- Distributionsspezifische Konfiguration --- distro_configs = { "arch": { "update": "pacman -Syu --noconfirm", "install": "pacman -S --noconfirm", "ssh_package": "openssh", "ssh_service": "sshd.service", "pre_install_cmds": [ ("Pacman-Schlüsselbund initialisieren", "pacman-key --init"), ("Pacman-Schlüsselbund füllen", "pacman-key --populate archlinux") ], "user_groups": "users,wheel" }, "ubuntu": { "update": "apt-get update && apt-get upgrade -y", "install": "apt-get install -y", "ssh_package": "openssh-server", "ssh_service": "ssh.service", "pre_install_cmds": [ ("Locales-Paket installieren", "apt-get install -y locales"), ("Locales generieren", "echo 'de_DE.UTF-8 UTF-8' > /etc/locale.gen && echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen && locale-gen") ], "user_groups": "users,sudo" }, "debian": { "update": "apt-get update && apt-get upgrade -y", "install": "apt-get install -y", "ssh_package": "openssh-server", "ssh_service": "ssh.service", "pre_install_cmds": [ ("Locales-Paket installieren", "apt-get install -y locales"), ("Locales generieren", "echo 'de_DE.UTF-8 UTF-8' > /etc/locale.gen && echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen && locale-gen") ], "user_groups": "users,sudo" }, "fedora": { "update": "dnf upgrade -y", "install": "dnf install -y", "ssh_package": "openssh-server", "ssh_service": "sshd.service", "pre_install_cmds": [], "user_groups": "users,wheel" } } if distro not in distro_configs: print(f"FEHLER: Nicht unterstützte Distribution: {distro}", file=sys.stderr) sys.exit(1) config = distro_configs[distro] print(f"Starte die Konfiguration für Container '{hostname}' mit Distribution '{distro}'...") # --- Allgemeine Konfiguration --- run_command("passwd", "Root-Passwort setzen", input_str=password_input) run_command(f"echo '{hostname}' > /etc/hostname", "Hostname setzen") run_command("ln -sf /usr/share/zoneinfo/Europe/Berlin /etc/localtime", "Zeitzone setzen") run_command("echo 'LANG=de_DE.UTF-8' > /etc/locale.conf", "Standardsprache setzen") if distro != "fedora": # Fedora hat andere Keyboard-Settings run_command("echo 'KEYMAP=de-latin1' > /etc/vconsole.conf", "Tastaturlayout setzen") # --- Distributionsspezifische Befehle ausführen --- for description, command in config["pre_install_cmds"]: run_command(command, description) run_command(config["update"], "System aktualisieren") run_command(f"{config['install']} {config['ssh_package']}", "OpenSSH installieren") # Störende Cloud-Init-Konfiguration entfernen, die Passwort-Auth blockiert run_command("rm -f /etc/ssh/sshd_config.d/60-cloudimg-settings.conf", "Entferne Cloud-Image-SSH-Einstellungen", input_str=None) # --- SSH und Benutzerkonfiguration --- run_command(f"systemctl enable {config['ssh_service']}", "SSH-Dienst aktivieren") run_command("sed -i 's/^#*PermitRootLogin.*/PermitRootLogin yes/' /etc/ssh/sshd_config", "Root-Login in sshd_config erlauben") run_command("sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config", "Passwort-Authentifizierung in sshd_config erlauben") run_command("sed -i 's/^#*LogLevel.*/LogLevel DEBUG3/' /etc/ssh/sshd_config", "SSH LogLevel DEBUG3 setzen") run_command(f"systemctl restart {config['ssh_service']}", "SSH-Dienst neustarten") # Benutzer 'jonnybravo' erstellen und sudo-Rechte geben wheel_group_equivalent = "wheel" if distro in ["arch", "fedora"] else "sudo" run_command(f"useradd -m -G {config['user_groups']} -s /bin/bash jonnybravo", "Benutzer 'jonnybravo' hinzufügen") run_command("passwd jonnybravo", "Passwort für jonnybravo setzen", input_str=password_input) if wheel_group_equivalent == "wheel": run_command("echo '%wheel ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/wheel_nopasswd", "Passwortloses sudo für Gruppe 'wheel' aktivieren") else: # sudo group run_command("echo '%sudo ALL=(ALL) NOPASSWD: ALL' > /etc/sudoers.d/sudo_nopasswd", "Passwortloses sudo für Gruppe 'sudo' aktivieren") print(f"\n=== Container '{hostname}' erfolgreich konfiguriert! ===") if __name__ == "__main__": main()