Files
Boilerplates/Ansible/ssh-keyscan.sh

55 lines
1.7 KiB
Bash
Raw Permalink 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 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