How to add SSH known host in a bash script?

Solution 1:

The simple way to go would be to do something like this.

ssh-keyscan remote_server >>~/.ssh/known_hosts

If this box is brand new you might also need to create the ~/.ssh directory before you run ssh-keyscan.

Keep in mind that ssh-keyscan can take an arbitrary number of hostnames. It will get all the keys it can.

Solution 2:

Are you trying to automate accepting the new key? If so, you could use -oStrictHostKeyChecking=no.
Doing so is a very bad idea as you're now completely wide open to man-in-the-middle attacks.

A better option would be just to manage a known_hosts file and reuse that file when you provision new servers. Stick it on github and write a simple script to download that file before sshing into github.

The strict host key checking is a good thing.

Solution 3:

I'm not sure i understand the question, but i think you want to ignore the known_host prompt or avoid it entirely, in which case:

ssh -o StrictHostKeyChecking=no

or other suggestions at: http://www.joedog.org/2012/07/ssh-disable-known_hosts-prompt/