Configuring SSH to use a public / private key pair instead of a password

Sick of passwords? Simplify your life by configuring your SSH connection to use a public / private key pair instead.

Before you get started, confirm you have SSH access to the remote server, as you’ll need it shortly.

  1. Generate the public / private key pair via the command-line:
    ssh-keygen -t rsa

    The -t flag indicates the type of encryption you want to use to generate the keys, RSA or DSA. I use RSA for all these reasons and more.

  2. You’ll be prompted to name the key file. Choose something short and easy to remember. You can also provide the name as part of the initial command, using the -f flag (for output_keyfile):
    ssh-keygen -t rsa -f ~/.ssh/[key file name]
  3. You’ll be prompted to provide, then confirm, a passphrase. Hit enter both times to leave it blank.
  4. You’ll receive a success message, along with your key’s randomart image. (Curious about what it’s for?)
  5. Next, use the cat command to copy the public key from your local .ssh subdirectory to a file named authorized_keys in the .ssh subdirectory on remote server (creating the subdirectory if it doesn’t already exist):
    cat ~/.ssh/[key file name].pub | ssh [username]@[remote server] "mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"
  6. When prompted, type “yes” to confirm you want to continue connecting. This will add the connection to your local known_hosts file.
  7. When prompted, enter your SSH password.

Test everything by trying to connect to the server. You should be able to connect without being prompted for a password.

If you are prompted for a password, log in again with the -v flag (for verbose mode):

ssh -v [username]@[remote server]

If you see references to “id_rsa” or “id_dsa” in the output, SSH is trying to use the default key pair instead of the custom key pair you just created. Correct this by adding your custom keypair to SSH:

ssh-add ~/.ssh/[key file name]

Once your connection is set up, simplify things even further by adding the connection to your SSH config file.