Connect to your server using SSH keys

Submitted by alexandru on Fri, 12/08/2017 - 16:11
Article Topics

Connect to your server using SSH keys In this article I will show you how to connect to your server using SSH secure keys. For this, I will use a local Ubuntu 16.04.3 system, and I will connect to a server running Debian 9 Stretch. The steps are: 1 First you will have to run the command:

ssh-keygen -t rsa

this will create two new file into your .ssh directory from your home directory. One file will contain the public rsa key (id_rsa.pub) and the other will contain the private rsa key (id_rsa). The private file you will have to keep as safe as possible! The output is:

alexandru@alex-desktop:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/alexandru/.ssh/id_rsa):
Created directory '/home/alexandru/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/alexandru/.ssh/id_rsa.
Your public key has been saved in /home/alexandru/.ssh/id_rsa.pub.
The key fingerprint is:

You can also use the ssh-keygen command with the -b option, which sets the length in bytes: 4096, 2048, 1024. We recommend at least 2048, or 4096 for a greater strength of the encrypted key. 2 Now you will need to connect to your server using your password, with the command:

alexandru@alex-desktop:~$ ssh -p 2222 username@XX.XXX.XXX.XXX

where the "XX.XXX.XXX.XXX" should be your server's public IP, and "username" is your username from the server. You will be asked for your password and then you are in. You will do a update and, if available, upgrade:

sudo apt update
sudo apt ugrade

Then get back to your local system. 3 Copy the id_rsa.pub file from your local system to the server using scp:

alexandru@alex-desktop:~$ scp -P 2222 /home/alexandru/.ssh/id_rsa.pub username@XX.XXX.XXX.XXX:/home/username/
username@XX.XXX.XXX.XXX's password:
id_rsa.pub 100% 404 0.4KB/s 00:00

4 Connect to the server again, using ssh and your password:

alexandru@alex-desktop:~$ ssh -p 2222 username@XX.XXX.XXX.XXX

5 Copy the id_rsa.pub to the .ssh directory and rename it "authorized_keys"

alexandru@debian:~$ cp id_rsa.pub /home/alexandru/.ssh/
alexandru@debian:~/.ssh$ mv id_rsa.pub authorized_keys
alexandru@debian:~/.ssh$ ls -l
total 4
-rw-r--r-- 1 alexandru alexandru 404 Sep 26 13:34 authorized_keys

In case you still can’t log in using your ssh key and you receive an error similar to this: “ign_and_send_pubkey signing failed agent refused operation” then make sure to add your rsa_id using, on your local system, the command:

alexandru@debian:~> ssh-add
Identity added: /home/alexandru/.ssh/id_rsa (/home/alexandru/.ssh/id_rsa)

6 Exit from your server and try to connect again using the ssh command. You will notice that you will no longer be asked for your password and the connection will be done in just a few seconds.    

Tags