1

I have a file that contains ~1000 hosts, one host per line. For each host, I want to check if an entry for the host already exists in the known_hosts file. If one does not, I want to add the host to the known_hosts file. Otherwise, I want to update the existing entry. I would like to use the -H option to hash all entries in known_hosts. I have already run the command ssh-keygen -H ~/.ssh/known_hosts to hash the existing entries.

Here is a simple loop that I put together:

while read LINE; do
    # Remove entry if it exists
    ssh-keygen -R $LINE
    # Append new hashed key to file
    ssh-keyscan -H $LINE >> ~/.ssh/known_hosts
done < $HOST_FILE

Is this method secure? If not, what is the recommended way of doing this? The reason I am doing this is to disable typing "yes" 1000 times to allow every new host to be added to known_hosts for scripting purposes.

mwalto7
  • 307
  • 6
  • 19
  • Take a look at this: [https://stackoverflow.com/questions/3804577/have-bash-script-answer-interactive-prompts](https://stackoverflow.com/questions/3804577/have-bash-script-answer-interactive-prompts) – Leslie May 22 '18 at 20:12

1 Answers1

1

What's interactive here? You're piping data into your while loop and neither of the commands in the loop involve user interactivity. I see this as secure.

Note: ssh-keyscan drops comments to standard error and you might want to filter them out. You probably also don't need the errors from ssh-keygen when the requested host isn't present:

while read LINE; do
    # Remove entry if it exists
    ssh-keygen -R "$LINE" 2>/dev/null
    # Append new hashed key to file
    ssh-keyscan -H "$LINE" >> ~/.ssh/known_hosts 2>/dev/null
done < "$HOST_FILE"

You may also be interested in ssh-hosthashes, a script I wrote a while back that looks for duplicate entries in known_hosts files. This finds duplicates by the public keys, so it will cluster entries regardless of whether they are listed by IP, name, or hash.

Adam Katz
  • 14,455
  • 5
  • 68
  • 83