Can I automatically add a new host to known_hosts?

Solution 1:

IMO, the best way to do this is the following:

ssh-keygen -R [hostname]
ssh-keygen -R [ip_address]
ssh-keygen -R [hostname],[ip_address]
ssh-keyscan -H [hostname],[ip_address] >> ~/.ssh/known_hosts
ssh-keyscan -H [ip_address] >> ~/.ssh/known_hosts
ssh-keyscan -H [hostname] >> ~/.ssh/known_hosts

That will make sure there are no duplicate entries, that you are covered for both the hostname and IP address, and will also hash the output, an extra security measure.

Solution 2:

Set the StrictHostKeyChecking option to no, either in the config file or via -o :

ssh -o StrictHostKeyChecking=no [email protected]


Solution 3:

For the lazy ones:

ssh-keyscan -H <host> >> ~/.ssh/known_hosts

-H hashes the hostname / IP address


Solution 4:

As mentioned, using key-scan would be the right & unobtrusive way to do it.

ssh-keyscan -t rsa,dsa HOST 2>&1 | sort -u - ~/.ssh/known_hosts > ~/.ssh/tmp_hosts
mv ~/.ssh/tmp_hosts ~/.ssh/known_hosts

The above will do the trick to add a host, ONLY if it has not yet been added. It is also not concurrency safe; you must not execute the snippet on the same origin machine more than once at the same time, as the tmp_hosts file can get clobbered, ultimately leading to the known_hosts file becoming bloated...


Solution 5:

You could use ssh-keyscan command to grab the public key and append that to your known_hosts file.