Copy the SSH public key to a remote server

Updated: 2022-04-02

By generating private/public key and using it for authentication, it will improve the security of your SSH server.

By copying the SSH public key to the SSH remote server, it will allow you to connect to that server passwordless (by using only with the username and the private key).

After doing this, I advise you to change the SSH server configuration to disallow username/password logins for further security improvement.

The OS I chose to do this is Ubuntu, but these methods will probably work on most Linux distribution.

  1. The ssh-copy-id method

The easiest way to copy the public key is to use the ssh-copy-id command.

ssh-copy-id <user>@<your-remote-host>
  1. Copy over SSH method (alternative method)

If you do not have access to ssh-copy-id command, you can use this:

cat ~/.ssh/id_rsa.pub | ssh <user>@<your-remote-host> 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'
  1. Copy/paste method (alternative method)

Connect to the remote server:

ssh <user>@<your-remote-host>

Create the ~/.ssh directory:

mkdir -p ~/.ssh

Open the ~/.ssh/authorized_keys file:

nano ~/.ssh/authorized_keys

and paste the public that you copied in clipboard.

Note: The SSH server configuration must accept the authentication method via public/private key.

Resources: