How to: Connect to any Unix machine via SSH using a private key

This tutorial will be following on from my previous tutorial where I showed you how to setup secure logins on Ubuntu and I will now be showing you how you can use the keys created there to actually login from any unix based machine.

The first step is to get the private key we setup in the first tutorial. I will be assuming that this is in the default location but if you changed this, you will need to use that new location here.

The file should be stored within the .ssh directory inside your home folder called id_rsa. If you open this up, you can copy the key. If you are unsure how to copy from the terminal, you can just open the file with nano, select all of the text and then right click. This will then copy the selected text and paste it in the current location. You can then close the file without saving.

nano ~/.ssh/id_rsa

The key should look something a little like this:

Using the key

Saving the key

Once you have copied the key, you are ready to use it. You first need to save the key into a file on the local machine. For this, I will be saving it into a folder called keys within my home directory. If you would like to do this but dont have this setup, you can create it using this command.

mkdir ~/keys/

We now need to create the file and paste in the key. I will be calling the key after the name of the server. After that, you can save and exit. (Ctrl + O to Save and Ctrl + X to exit)

nano ~/keys/electra.key

Permissions

For you to use this to connect to the server, you will need to make sure that the permissions of the file indicate that only you can read and write to the file. If not, you will get an error message like the one below. Its style may change depending on the OS you are using.

After the key has been saved, we can now use this to connect. The syntax for this command is.

ssh username@hostname -i /path/to/private.key

An example of this is

ssh wilson18@electra.basicsysadmin.com -i ~/keys/electra.key

After you have done this, you may get a warning asking if you would like to trust this server, just type in yes. Also, if you did decide to encrypt the key, this is where you would also be asked for the passphrase for it.