How to instantly add known_hosts entries for host and its IP address

Use simple shell function to instantly create known_hosts entries for specified host including its IP address and remove outdated public host keys.

Get single SSH public key

add_known_host function that requires two parameters: key type and hostname.

function add_known_host() {
  if [ "$#" -eq "2" ]; then
    key_type=$1 # rsa, dsa, ecdsa or ed25519
    host=$2
    (echo $host; dig -t A +short $host) | \
      xargs -I HOST ssh-keyscan -t $key_type HOST 2>/dev/null | \
      cat - ~/.ssh/known_hosts  | \
      sort -k 1,2 -u > ~/.ssh/known_hosts.temp
    cmp --silent ~/.ssh/known_hosts ~/.ssh/known_hosts.temp
    if [ "$?" -gt "0" ]; then
      echo "Applied differences for $host:"
      diff --label "original file" --label "updated file" --unified=0 ~/.ssh/known_hosts ~/.ssh/known_hosts.temp
      #mv ~/.ssh/known_hosts.temp ~/.ssh/known_hosts
    fi
  fi
}

Sample usage.

$ add_known_host ecdsa cloud.fishsilentcruise.space
Applied differences for cloud.fishsilentcruise.space:
--- original file
+++ updated file
@@ -2,0 +3 @@
+192.168.88.232 ecdsa-sha2-nistp256 AAAAE2V...Jqqbf0=
@@ -20,0 +22 @@
+cloud.fishsilentcruise.space ecdsa-sha2-nistp256 AAAAE2V...Jqqbf0=

Get multiple SSH public keys

add_known_hosts function that accepts multple parameters as hostnames.

function add_known_hosts() {
  if [ "$#" -gt "0" ]; then
    for host in "[email protected]"; do
      (echo $host; dig -t A +short $host) | \
        xargs -I HOST ssh-keyscan -t rsa HOST 2>/dev/null | \
        cat - ~/.ssh/known_hosts  | \
        sort -k 1,2 -u > ~/.ssh/known_hosts.temp
      cmp --silent ~/.ssh/known_hosts ~/.ssh/known_hosts.temp
      if [ "$?" -gt "0" ]; then
        echo "Applied differences for $host:"
        diff --label "original file" --label "updated file" --unified=0 ~/.ssh/known_hosts ~/.ssh/known_hosts.temp
        mv ~/.ssh/known_hosts.temp ~/.ssh/known_hosts
      fi
    done
  fi
}

Sample usage.

$ add_known_host wiki.sleeplessbeastie.eu cloud.sleeplessbeastie.eu
Applied differences for wiki.sleeplessbeastie.eu:
--- original file
+++ updated file
@@ -0,0 +1 @@
+192.168.88.103 ssh-rsa AAAAB3N...FfO6cZN
@@ -17,0 +19 @@
+wiki.sleeplessbeastie.eu ssh-rsa AAAAB3N...FfO6cZN
Applied differences for cloud.sleeplessbeastie.eu:
--- original file
+++ updated file
@@ -1,0 +2 @@
+192.168.88.232 ssh-rsa AAAAB3N...QUjCycf
@@ -18,0 +20 @@
+cloud.sleeplessbeastie.eu ssh-rsa AAAAB3N...QUjCycf
Milosz Galazka's Picture

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.