Top Web Hosts >> Forums >> Technical Articles

Setting up trusted ssh environment with public/private key pair

The procedure described below explains the steps necessary to make two machines trusted environment. By making one machine trusted by another, password prompt is bypassed when ssh command is invoked "local" host. This is useful when making automated backup using tar or rsync. For description purpose, we use "local" machine to denote a machine that a user is logged on to perform the backup, "remote" machine to denote a machine that will be used to store the backup of the local machine data. It is assumed that we're making a backup between two Linux boxes.

A. Create a trusted host environment between local and remote machines.
To be able to execute a command using ssh without being prompted for a password, you'll need to generate a ssh key that will be used to create a trusted environment between servers. For the purpose of this illustration, we'll assume that a user called "scott" will perform the backup.

1. Login to a local machine as a user named "scott". This user can be anyone with a permission to read and create backup of a local content.

2. Generate private/public key pair using the "ssh-keygen" command.

% ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/scott/.ssh/id_rsa):

The command prompts for a file name, and pass-phrase. Take the default answers by pressing "Enter" key three times.

Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/scott/.ssh/id_rsa.
Your public key has been saved in /home/scott/.ssh/

The command above creates 2 files in the .ssh directory inside the user's home directory. The ~scott/.ssh/id_rsa is the private key, and ~scott/.ssh/ is the public key. The private key should not be shared with anyone, so make it read-only for yourself (default).

% chmod 600 ~scott/.ssh/id_rsa

3. Copy public key on the remote server.
In order to create a trusted environment, we need to place the local machine's public key in the remote machine. We'll add public key entry in the remote machine in the ~scott/.ssh/authorized_keys2. In case .ssh directory may not exists in the remote machine, perform the following to create the directory. Replace hostname inside curly braces with actual hostname.

% ssh {remote-host} "mkdir .ssh; chmod 600 .ssh"
% scp ~scott/.ssh/ {remote-host}:~scott/.ssh/{local-host}.pub
% ssh {remote-host} cat ~scott/.ssh/{local-host}.pub >> ~scott/.ssh/authorized_keys2

Enter password when prompted. You should be able to execute a commmand on a remote machine without supplying a password. Test the setup by performing the following:

% ssh {remote-host} ls

If command executed without password, the setup is good and we can proceed to the next step. If password is prompted, go back to step 2 above.