Easiest way to copy ssh keys to another machine?
I am lazy at home and use password authentication for my home machines. I am ready to move to key based authentication. There are many options on the web on how to do this, including catting then sshing the key over, scping the key over directly, etc.
I am looking for the easiest and recommended way to copy a key over, hopefully there is a convenience wrapper somewhere in the Ubuntu ssh package?
I'm already aware on how to shut off password logins.
Solution 1:
The ssh-copy-id
command (in the openssh-client package and installed by default) does exactly this:
ssh-copy-id [email protected]
copies the public key of your default identity (use -i identity_file
for other identities) to the remote host.
The default identity is your "standard" ssh key. It consists of two files (public and private key) in your ~/.ssh
directory, normally named identity
, id_rsa
, id_dsa
, id_ecdsa
or id_ed25519
(and the same with .pub
), depending on the type of key. If you did not create more than one ssh key, you do not have to worry about specifying the identity, ssh-copy-id will just pick it automatically.
In case you do not have an identity, you can generate one with the tool ssh-keygen
.
In addition, if the server uses a port different from the default one (22
) you should use quotation marks in this way (source):
ssh-copy-id "[email protected] -p <port-number>"
Solution 2:
I like the answer from Marcel. I did not know this command. I've always been using what I had found on the Oracle web site:
cat ~/.ssh/id_rsa.pub | ssh <user>@<hostname> 'cat >> .ssh/authorized_keys && echo "Key copied"'
I thought to post it here still, because it is a good illustration of what can be achieved in shell code with the power of ssh
. But using the ssh-copy-id
is definitively a safer way to do it properly!
Note that if the folder .ssh
does not already exist, the above command will fail. In addition, it might be better when creating the file to set a minimum possible permission (basically read-write for owner only). Here is a more advanced command:
cat ~/.ssh/id_rsa.pub | ssh <user>@<hostname> 'umask 0077; mkdir -p .ssh; cat >> .ssh/authorized_keys && echo "Key copied"'
Solution 3:
Graphical method
- Open Applications ▸ Passwords and Keys ▸ My Personal Keys.
- Select your key and then click Remote ▸ Configure Key for Secure Shell.