Update Ansible/ssh-keyscan.sh

This commit is contained in:
2025-05-07 08:02:49 +00:00
parent f4c684b51d
commit c595a9fdcc

View File

@@ -1,33 +1,41 @@
#!/usr/bin/env bash
#!/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 -euo pipefail
set -eu
# ---------- Root-Check (sofort & sicher) --------------
script_path=$(readlink -f "$0") # absoluter Pfad des Skripts
# ---------- 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
sudo -v # 1× Passwort, Timestamp bleibt gültig
exec sudo -- "$script_path" "$@" # ersetzt Prozess, KEIN zweiter Prompt
printf "${BLUE}🔐 Root-Rechte erforderlich starte mit sudo ...${RESET}\n"
sudo -v
exec sudo sh "$script_path" "$@"
fi
# ---------- Eingabe ----------------------------------
read -rp "Bitte die Ziel-IP eingeben: " ip
# ---------- 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
echo " Für $ip existiert bereits ein Eintrag in /etc/ansible/known_hosts."
echo " Bitte prüfe ihn manuell, falls du unsicher bist."
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)
ssh-keyscan -H "$ip" 2>/dev/null >"$tmp"
if [[ ! -s $tmp ]]; then
echo "❌ Kein Host-Key empfangen ist Port 22 offen?"
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
@@ -38,9 +46,9 @@ rm -f "$tmp"
# ---------- Verifikation ------------------------------
if ssh-keygen -F "$ip" -f /etc/ansible/known_hosts >/dev/null 2>&1; then
echo "✓ Host-Key für $ip wurde erfolgreich hinzugefügt."
printf "${GREEN}✓ Host-Key für %s wurde erfolgreich hinzugefügt.${RESET}\n" "$ip"
exit 0
else
echo "❌ Eintrag ließ sich nicht verifizieren!"
printf "${RED}❌ Eintrag ließ sich nicht verifizieren!${RESET}\n"
exit 2
fi