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

created by BasicSysAdmin

Tags: Linux, Ubuntu, Ubuntu 14.04, Ubuntu 15.04, SSH

May 26, 2016


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.

In order to follow this tutorial, you will need the following

  • Tutorial: How to: Securely login with SSH Keys on Ubuntu

    Getting the Private Key

    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


    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.

    Permissions 0644 for 'keys/electra.key' are too open.
    It is required that your private key files are NOT accessible by others.
    This private key will be ignored.
    bad permissions: ignore key: keys/electra.key
    wilson18@electra.basicsysadmin.com's password:

    You can set the appropriate permissions for this using this command:

    chmod 700 ~keys/electra.key


    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.