How to use SSH to connect to a Linux server without typing the password

1. Generate local key pairs

Firstly, you need to generate key pairs in your local Linux box:

$ ssh-keygen

You are going to see the output like this:

Generating public/private rsa key pair.

Enter file in which to save the key (/home/zhouhon1/.ssh/id_rsa):

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/zhouhon1/.ssh/id_rsa.

Your public key has been saved in /home/zhouhon1/.ssh/id_rsa.pub.

The key fingerprint is:

96:d3:8d:0e:d9:bf:af:fd:18:2e:67:3d:b3:19:a4:f8 zhouhon1@bl210xwks-004w.srunet.sruad.edu

Press Enter to accept default file location to save key pairs, and a strong passphrase for your key files.

2. Upload public key file to Linux server

File ~/.ssh/id_rsa.pub contains the public key of the local Linux box. We need to upload this file to the Linux server, so the server can use the public key to authenticate the user:

$ scp .ssh/id_rsa.pub zhou@cs.sru.edu:~/

zhou@cs.sru.edu's password:

id_rsa.pub 100% 422 0.4KB/s 00:00

3. Append id_rsa.pub to ~/.ssh/authorized_keys file

The last step is append the public key of our local Linux box to the end of .ssh/authorized_keys file in the Linux server, so our local Linux box can be automatically authenticated.

$ cat ~/id_rsa.pub >> ~/.ssh/authorized_keys

Now we do not need the public key file in the Linux server any more, so we can safely delete it in the Linux server:

$ rm ~/id_rsa.pub

4. Use SSH agent to avoid typing password

If you choose an empty passphrase for your key files in step 1, you do not need to type any password to connect to the Linux server. However, if you choose a passphrase, you need to type it when connecting to the server:

ssh zhou@cs.sru.edu

Enter passphrase for key '/home/zhouhon1/.ssh/id_rsa':

It will soon be boring to do it again and again. However, with SSH agent, you can load the key file to the memory and type the passphrase for once and then initiate the connection without typing the passphrase again:

$ ssh-agent $SHELL

$ ssh-add

Enter passphrase for /home/zhouhon1/.ssh/id_rsa:

Identity added: /home/zhouhon1/.ssh/id_rsa (/home/zhouhon1/.ssh/id_rsa)

$ ssh zhou@cs.sru.edu

Firstly, we run ssh-agent followed by the Shell program to run another Shell process, so all the programs running in that Shell process can talk with the agent. Then we run ssh-add to load the key file. In the example, the default key file is loaded, but you can also specify another key file to load. After the key file is loaded, you can run ssh or scp to log into the Linux server or transfer files without typing the password.

P.S. You can use ssh-add -l to list all the loaded key, and ssh-add -d <key filename> or ssh-add -D to delete one key or all the keys.