SSH with Public Key-Based Authentication

To improve the system security and to enable running automated maintenance tasks on other machines, you can use the key-based authentication instead of standard password authentication.

Key-based authentication uses two keys, one “public” key that anyone is allowed to see, and another “private” key that only the owner is allowed to see.

To securely communicate using key-based authentication, you need to create a public key for the computer you’re logging in from, and securely transmit it to the computer you’re logging in to.

1. Generating a key pair on the local computer

Note that keys must be generated for each user separately.

Create a directory if it doesn’t already exist and set the permissions:

$ mkdir -p ~/.ssh
$ chmod 700 ~/.ssh

Enter the directory and generate public/private RSA key pair:

$ cd ~/.ssh
$ ssh-keygen -t rsa

You can add comment to your public key:
$ ssh-keygen -t rsa -C “A comment… usually an email is enough here…”

Copy the public key to the remote host:

$ scp -p id_rsa.pub RemoteUser@RemoteHost

2. Connecting to the remote server and installing the public key

$ ssh RemoteUser@RemoteHost
Password: ********

Create a directory if it doesn’t already exist and set the permissions:

RemoteHost$ mkdir -p ~/.ssh
RemoteHost$ chmod 700 ~/.ssh

Copy the public key to ‘authorized_keys’ file and set the permissions:

RemoteHost$ cat id_rsa.pub >> ~/.ssh/authorized_keys
RemoteHost$ chmod 600 ~/.ssh/authorized_keys

Remove the public key from the home directory and log out:

RemoteHost$ rm -f ~/id_rsa.pub
RemoteHost$ logout

3. Adding the private key to the authentication agent on the local server

$ ssh-add
Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)

Now you can log into the remote server via the SSH protocol without a password.