Methods to add ssh key to the server
In this tutorial, we will show you the methods to copy the public ssh key to the server. The public-key authentication method requires you to copy your public SSH key to the server’s authorized_keys file. You might be wondering why we need to add the SSH key to the server as the reason to add ssh key to the server is to allow you to access a server via SSH without a password. Here are two methods to copy the public ssh key to the server.
How To Add SSH Key To Server
Let’s go through the process of adding the ssh key to the server.
Copy ssh public key to remote server using ssh-copy-id:
In this very first 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.
Manually copy the public ssh key to the server
In another method, 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.
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
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