Connecting via SSH key is more secure than connecting via passwords. This is especially true if the only method you can SSH into a machine is via key. Connecting via SSH Key is also handy when you need to automate script connection without passwords. Here is how it is done:

Generating the SSH Key

  1. Connect to each machine from the other machine via SSH (IE: ssh machine1.com, ssh machine2.com). This will create a .ssh directory in your home directory with the proper permissions. This directory may already be present.

  2. On the machine you wish to connect to the other machine from (via SSH Key Authentication), generate a key by issuing this command:

    ssh-keygen -t dsa

    You will see:

    Generating public/private dsa key pair.
    Enter file in which to save the key (/home/username/.ssh/id_dsa):

  3. Press enter to leave the path as default
    You will see:

    Enter passphrase (empty for no passphrase):

  4. Enter a passphrase or press enter to leave it blank. If you want to connect to the remote machine without a password, leave this field blank. This is particularly useful in Linux scripts that need to be automatic (without password.
    You will see:

    Enter same passphrase again:

  5. Enter the same passphrase again or press enter to leave it blank

  6. Your key will be generated in the path you chose at step 2/3. You will also see some ASCII Art.

Transferring the SSH Key to the Remote Machine

Transferring the key to the remote machine is easy. You transfer the public key which was generated in step 6 above. Here is how:

  1. Execute this command:

    scp ~/.ssh/id_dsa.pub [username]@[host.com]:.ssh/authorized_keys2

  2. Enter the password of the user on the remote host.

That’s it. You should now be able to connect from the primary machine (from step 2 in the first section) using your SSH key. If you left the passphrase blank you will be able to connect without having to enter a password.  Test it by connecting via SSH from the primary machine:

ssh [username]@[host.com]