#!/usr/bin/env sh # ssh-keyscan.sh # Fügt den SSH-Host-Key einer IP in /etc/ansible/known_hosts ein # ohne doppelte Passwortabfrage, ohne Doppel-Einträge, mit Verifikation. # POSIX-kompatibel, farbige Ausgabe set -eu # ---------- Farben ------------------------------------ RED="\033[0;31m" GREEN="\033[0;32m" YELLOW="\033[1;33m" BLUE="\033[1;34m" RESET="\033[0m" # ---------- Root-Check -------------------------------- script_path=$(readlink -f "$0") if [ "$(id -u)" -ne 0 ]; then printf "${BLUE}🔐 Root-Rechte erforderlich – starte mit sudo ...${RESET}\n" sudo -v exec sudo sh "$script_path" "$@" fi # ---------- Eingabe ----------------------------------- printf "${BLUE}👉 Bitte die Ziel-IP eingeben: ${RESET}" read ip # ---------- Vorhandenen Eintrag prüfen ---------------- if ssh-keygen -F "$ip" -f /etc/ansible/known_hosts >/dev/null 2>&1; then printf "${YELLOW}ℹ️ Für %s existiert bereits ein Eintrag in /etc/ansible/known_hosts.\n" "$ip" printf " Bitte prüfe ihn manuell, falls du unsicher bist.${RESET}\n" exit 0 fi # ---------- Host-Key abrufen -------------------------- tmp=$(mktemp) if ! ssh-keyscan -H "$ip" 2>/dev/null >"$tmp" || [ ! -s "$tmp" ]; then printf "${RED}❌ Kein Host-Key empfangen – ist Port 22 offen?${RESET}\n" rm -f "$tmp" exit 1 fi # ---------- Key anhängen ------------------------------ cat "$tmp" >> /etc/ansible/known_hosts rm -f "$tmp" # ---------- Verifikation ------------------------------ if ssh-keygen -F "$ip" -f /etc/ansible/known_hosts >/dev/null 2>&1; then printf "${GREEN}✓ Host-Key für %s wurde erfolgreich hinzugefügt.${RESET}\n" "$ip" exit 0 else printf "${RED}❌ Eintrag ließ sich nicht verifizieren!${RESET}\n" exit 2 fi