Add Ansible/ssh-keyscan.sh

This commit is contained in:
2025-05-07 06:18:54 +00:00
parent a634641082
commit 704d968900

46
Ansible/ssh-keyscan.sh Normal file
View File

@@ -0,0 +1,46 @@
#!/usr/bin/env bash
# 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.
set -euo pipefail
# ---------- Root-Check (sofort & sicher) --------------
script_path=$(readlink -f "$0") # absoluter Pfad des Skripts
if [[ $EUID -ne 0 ]]; then
sudo -v # 1× Passwort, Timestamp bleibt gültig
exec sudo -- "$script_path" "$@" # ersetzt Prozess, KEIN zweiter Prompt
fi
# ---------- Eingabe ----------------------------------
read -rp "Bitte die Ziel-IP eingeben: " 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."
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?"
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
echo "✓ Host-Key für $ip wurde erfolgreich hinzugefügt."
exit 0
else
echo "❌ Eintrag ließ sich nicht verifizieren!"
exit 2
fi