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.

Tags:

Bash

Ssh