Methods to add ssh public key to the server

We will demonstrate how to copy the public SSH key to the server in this tutorial. You must copy your public SSH key to the server’s authorized_keys file in order to use the public-key authentication method. The purpose of adding an SSH key to the server is to provide password-free SSH access to a server. You may be questioning why this is necessary.

How To Add SSH Public Key To Server

The public SSH key can be copied to the server using these two techniques.

1. Copy ssh public key to remote server using ssh-copy-id:

In this  method, we will copy the ssh public key to the server using ssh-copy-id tool. In this process, we will copy the personal computer’s public key to the list of the authorized keys on the remote server. The authorized_keys file is in the ~/.ssh/

ssh-copy-id -i ~/.ssh/id_rsa.pub validusername@IP_ADDRESS_OF_THE_SERVER

When prompted, enter the password for your user account at the remote server. Your public key should be copied to the remote server.
~/.ssh/id_rsa.pub  is the default location for the public ssh key. If you want to use another public key rather than the one in the default location, use the -i option.

2. Manually copy the public ssh key to the server

In this method, we will take the help of manual method where we can manually copy the ssh key to the server.  This method is useful when your server doesn’t allow you ssh login via password. In this process, you need to ask the end-user to provide their pubic key at first.

cat ~/.ssh/id_rsa.pub

Manually append your public key to the remote ssh server’s key to the authorized_keys file. For example, copy the content of your ~/.ssh/id_rsa.pub to the server’s ~/.ssh/authorized_keys file.

Using the following command combination

cat ~/.ssh/id_rsa.pub | ssh user@remote-host 'cat >> ~/.ssh/authorized_keys'

Now, create new directories and files in the end user’s home directory so that you can add the public key of the end user that you have asked for in the previous step.


Now add the public key of the user in /home/user_name/.ssh/authorized_keys file

vim /home/username/.ssh/authorized_keys

Save and close the file.

Now, if your end-users tried to connect to a remote server then they might come across a permission denied error or something like this “r “sign_and_send_pubkey: signing failed: agent refused operation Permission denied (publickey)”.

One of the reasons for this is due to file permission on ssh file.  Make sure to set the correct file permissions:

chmod 700 /home/username/.ssh && chmod 600 /home/username/.ssh/authorized_keys

Change the ownership to the user:

chown -R username:username /home/username/.ssh

Now your end-user can log in to the server without any issue

Leave a comment

Your email address will not be published. Required fields are marked *