Using Public/Private Key Pairs with SSH

This is one of those subjects that is a little difficult to convey clearly. It is a logical process and not difficult…but it is precise in the sense that certain files must be correct, be in the right places and have correct permissions. I’ve organized these instructions in three parts, key generation; local (client) side setup; remote(server) side setup.

For more information about public/private keys, see the Wikipedia article.

1. Generating a Public/Private key Pair

The private key will be named whatever you specified and the public key will have that name appended with “.pub”. These keys will be located in the ~.ssh directory. For example, using the default name for a dsa key pair, the files will be “id_dsa” and “”. Always keep the private key private. The public key is not secret and can be put in unsecure locations.

You need to generate the correct type of key for the remote system you are dealing with. In this article, we are using a dsa type key as an example. If the remote system requires an rsa key pair, generate an rsa pair instead.

To generate dsa key pair:

ssh-keygen -t dsa

The program will ask a series of prompted questions. For our purposes, it is Ok to just keep pressing the enter key for the defaults. The generated keys will be stored in your ~/.ssh directory. See the generated keys with:

ls -l ~/.ssh

2. Setup on the Local Side

Ensure Correct Permissions

chmod 700 ~/.ssh
chmod 600 ~/.ssh/*

If directory or filename permissions are not correct, ssh will fail to use the keys.

Create a config File

For each remote system, create a multi-line entry in the ~.ssh/config text file. You can create this file using your favorite editor, vi for example. File contents (one group per server, one group shown):

Host friendly_server_name_here
HostName ip_number_here
IdentityFile ~/.ssh/id_dsa
PasswordAuthentication no
Port 22
User your_username_on_remote_here

Of course, replace the three bolded items with your information for your accounts.

Give the config file the correct permissions:

chmod 600 ~/.ssh/config

3. Setup on the Remote Side

Copy the public key file you generated from your local machine to the remote machine’s .ssh directory:

scp ~/.ssh/ username@servername:~/.ssh

Log in the remote machine for the next operations:

ssh username@servername

Append the contents of your public key file to ~/.ssh/the authorized_keys file:

cat ~/.ssh/ >> ~/.ssh/authorized_keys

Actually, the ~/.ssh/ file does not need to be there, just appended to the ~/.ssh/authorized_keys file. It was just convenient to do it this way.

Ensure Correct Permissions

chmod 700 ~/.ssh
chmod 600 ~/.ssh/*


Now you can login to the remote system with:

ssh username@servername

…and not need to enter a password!

Be Sociable, Share!

2 thoughts on “Using Public/Private Key Pairs with SSH

Comments are closed.