Files
Boilerplates/Ansible/ssh-keyscan.sh
2025-05-07 06:18:54 +00:00

46 lines
1.5 KiB
Bash
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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