Generating and using RSA keys for SSH logins

  Linux

Sometimes using an interactive SSH login to a remote system is not desired. For instance if you have created rsync scripts to automate backups of one system to another. A good way to automate this while maintaining a level of security is with the use of RSA encrypted keys shared between the machines you wish to connect. With the use of a public and private key, SSH connections can be made without the use of a password.

NOTE: Logging in with SSH as root should be avoided if possible

The following steps will allow you to connect two computers through SSH without using a password.

You will first need to generate the encrypted keys. One you will share with the computer you wish to connect and the other will be kept secret on the computer used to generate the keys.

Generating the keys is as simple as the following command:

$ ssh-keygen -t rsa
  Generating public/private rsa key pair.
  Enter file in which to save the key (/home/username/.ssh/id_rsa):
  Enter passphrase (empty for no passphrase):
  Enter same passphrase again:
  Your identification has been saved in /home/username/.ssh/id_rsa.
  Your public key has been saved in /home/username/.ssh/id_rsa.pub.

If in the generation of your keys, you do not wish to enter a password every time you wish to establish an SSH connection, leave the passphrase empty and just press ENTER at the prompt.

Once your keys have been generated you will want to copy the id_rsa.pub file to the system you wish to log in to. Using SCP is a good way of transferring the file.

$ scp .ssh/id_rsa.pub username@hostname.com:/home/username

Next connect to the system you transferred the id_rsa_pub file to and change to the directory of the uploaded file.

$ cd /home/username

You will now want to copy the file to the .ssh/authorized_keys file of the user. You can have multiple entries on the authorized_keys file so rather than risk overwriting the file, append your new key to it.

$ cat id_rsa.pub >> .ssh/authorized_keys

Make sure the permissions on the .ssh/authorized_keys file are set to 600 or you will error out.

You should now be able to SSH to the system you just added the key without using a password. Test with SSH.

$ ssh username@hostname.com

If all went well, you should now be able to connect without a password prompt.

LEAVE A COMMENT