How to add SSH key to server

We’ve already studied SSH (i.e., the Secure Socket Shell) in this shot. Now, let’s see how we could go about adding an SSH key to our server. By adding SSH keys, we can provide a more secure authentication mechanism than we could with just a password. With time, passwords, especially weak ones, can be broken with brute force, but such attacks are no match for SSH keys that are nearly impossible to decipher.

Generating a new SSH key

Before we can add an SSH key to our server, we need to have one at our disposal. Let’s generate one for this purpose. To do this, we need to run the following command in our terminal:
ssh-keygen -t rsa

The terminal will then prompt you to enter the file where you would like to store the key. If you are fine with the default file path, press enter. Next, you will be asked to enter a passphrase twice. If you wish not to have a passphrase, press enter.

The terminal below runs ssh-keygen -t rsa to produce an SSH key( id_rsa.pub) in the /root/.ssh/ default directory. Press “enter” until the key is generated.

Terminal 1
Terminal
Loading...

Alternatively, you can check for existing SSH keys you may want to use by typing ls -al ~/.ssh into the terminal.

Adding SSH key to server

Now that we have an SSH key, we can add it to our server with the following command:
cat ~/.ssh/id_rsa.pub | ssh user@host 'cat >> .ssh/authorized_keys''

In the command aboce, make sure to replace user with your own username and host with your server’s domain name or IP address.

When prompted for a password, enter the passphrase you entered when generating the SSH key.

Copyright ©2024 Educative, Inc. All rights reserved