Add public key to known_hosts file

This is how I did it.

  1. Generate a key on host server. Using the below command.

*ssh-keyscan -t rsa full-server-name

Command line and output

  1. Now copy the highlighted section(in the picture) and append this key to the ‘known_host’ file on source server. Of course, the location for this file could be different for different environments.

I answered almost similar answer on SuperUser few days ago. The important parts:

  • The format differs
  • There are different host keys (types) on each server (make sure you paste the one that is actually used)
  • There is ssh-keyscan which can create the format for you

Otherwise just prefix your key with server IP address (you can add also hostname, after comma), remove the comment from end of the line and you are fine. Format then look like this:

11.22.33.44 ssh-rsa AADGD...

And one more note, if you use HashKnownHosts yes (Debian and Ubuntu does), you need to re-hash your known_hosts such as:

ssh-keygen -Hf ~/.ssh/known_hosts

Having just bumped into this problem, here's how I approached it:

Over time, copying the files mechanically via

ssh-keyscan server-name >> ~/.ssh/known_hosts

gave me duplicate entries in .ssh/known_hosts.

Other manual methods required me to create the .ssh directory didn't already exist, etc.

I decided to just let ssh handle it:

ssh -o StrictHostKeyChecking=no server-name ls

The -o StrictHostKeyChecking=no option automatically answers 'yes' to the

The authenticity of host 'server-name (12.345.678.900)' can't be established.
RSA key fingerprint is XXXXXXX.
Are you sure you want to continue connecting (yes/no)?

message (insert here all the security caveats about connecting randomly to machines you don't know).

The ls command is just a fluff command that will execute and force SSH to disconnect when done. You can change it to whatever fluff command you like.

ssh will take care of creating the .ssh dir (if necessary), adding only one copy of the key, etc.

Platform: macOS 10.14

Tags:

Linux

Ssh

Key