3.2 Public key authentication

There is an alternative method to authenticate with SSH. The public key authentication method requires that a key pair be generated for a user. This can be done using the following command. First, Log in to the client machine as a normal user who need to use SSH to log in to an SSH server. Then execute the following command:

ssh-keygen  
    

This starts the interactive key generator. It prompts you to specify where to store the key pair files. Take the default by pressing the ENTER key.

Next, the key generator asks you for a passphrase. This is a safety feature so that even if someone gets a hold of the private key file, a passphrase is still required to use the private key file. While this is a good idea, in general, it does prevent the use of SSH for automated tasks. As a result, press ENTER and do not specify a passphrase.

When the key generator is done, it creates two files in the folder ~/.ssh. The first file is id_rsa. This is the private key file. Guard this file well, as anyone with this file can authenticate as you! The second file is id_rsa.pub, which is the public key file corresponding to id_rsa.

Next, you need to append the public key file to the ~/.ssh/authorized_keys file of an account on the SSH server. server.

If you suspect that you do not have a .ssh folder created, yet, on the server (remote) side, execute this command first:

ssh user@domainname "mkdir .ssh; chmod 700 .ssh"  
    

Once we are sure that we have the .ssh folder, then use the following command to set up the authorized public key:

cat ~/.ssh/id_rsa.pub | ssh user@domainname "cat >> ~/.ssh/authorized_keys"  
    

This command is a rather interesting use of Linux commands. Let us disect this command and see what it does:

Effectively, this long command appends the public key file (on the client machine) to the end of the special file authorized_keys (on the server machine). Once appended, the SSH server can use public key authentication.

On the client machine, try this again:

ssh user@domainname  
    

This time, the SSH server should find the public key and permit public key authentication without asking for any passwords.

Public key authentication is very useful for two purposes. First, it does not require the user to remember any passwords. Second, it permit automated authentication (because there is no need to enter any passwords). This permits automated tasks to be done remotely.