Scripting

Copy SSH Key One Liner

How to copy your ssh key to a remote machine without having to log in multiple times

I often have to set up new PCs? and it is a pain to have to scp the id file then ssh in and cat the contents.

There is a command ssh-copy-id which will do the trick along with checking permissions etc. However, I found that it can also hide errors meaning the copy does not work.

The following command will cat the contents of your id onto the end of the remote keys file. It won't do anything fancy, but if the remote PC is set up correctly, this will work fine:

cat ~/.ssh/id_rsa.pub | ssh <remote_server> "cat - >> ~/.ssh/authorized_keys" 

Alternative for scripting (eg Jenkins)

echo "Trying to log into ${SSH_HOST} with username ${SSH_USERNAME}."

ssh-keyscan -H ${SSH_HOST} >> ~/.ssh/known_hosts

SSHPASS="${SSH_PASSWORD}" sshpass -e ssh-copy-id ${SSH_USERNAME}@${SSH_HOST}