There are two steps to implement automatic authentication with SSH. They are as follows:
- Creating the SSH key on the local machine
- Transferring the public key to the remote host and appending it to ~/.ssh/authorized_keys (which requires access to the remote machine)
To create an SSH key, run the ssh-keygen command with the encryption algorithm type specified as RSA:
$ ssh-keygen -t rsa Generating public/private rsa key pair. Enter file in which to save the key (/home/username/.ssh/id_rsa): Created directory '/home/username/.ssh'. 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. The key fingerprint is: f7:17:c6:4d:c9:ee:17:00:af:0f:b3:27:a6:9c:0a:05 username@slynux-laptop The key'srandomart image is: +--[ RSA 2048]----+ | . | | o . .| | E o o.| | ...oo | | .S .+ +o.| | . . .=....| | .+.o...| | . . + o. .| | ..+ | +-----------------+
You need to enter a passphrase to generate the public-private key pair. It is possible to generate the key pair without entering a passphrase, but it is insecure.
If you intend to write scripts that use automated login to several machines, you should leave the passphrase empty to prevent the script from asking for a passphrase while running.
The ssh-keygen program creates two files. ~/.ssh/id_rsa.pub and ~/.ssh/id_rsa:id_rsa.pub is the generated public key and id_rsa is the private key. The public key has to be appended to the ~/.ssh/authorized_keys file on remote servers where we need to auto-login from the current host.
This command will append a key file:
$ ssh USER@REMOTE_HOST \
"cat >> ~/.ssh/authorized_keys" < ~/.ssh/id_rsa.pub
Password:
Provide the login password in the previous command.
The auto-login has been set up from now onwards, so SSH will not prompt for passwords during execution. Test this with the following command:
$ ssh USER@REMOTE_HOST uname Linux
You will not be prompted for a password. Most Linux distros include ssh-copy-id, which will append your private key to the appropriate authorized_keys file on the remote server. This is shorter than the ssh technique described earlier:
ssh-copy-id USER@REMOTE_HOST