Easiest way to copy ssh keys to another machine?

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>"

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"'

Graphical method

  1. Open ApplicationsPasswords and KeysMy Personal Keys.
  2. Select your key and then click RemoteConfigure Key for Secure Shell.

Set Up Computer for SSH Connection

Tags:

Ssh