Set Up SSH Public Key Authentication

1. Generate the SSH Key Pair

ssh-keygen -t rsa -b 2048
  • -t rsa specifies the type of key to create (RSA).
  • -b 2048 specifies the number of bits in the key, with 2048 being the recommended size for security.

You will be prompted to specify a file in which to save the key: You can press Enter to accept the default location. If you want to specify a different file, you can do so. You will also be prompted to enter a passphrase for added security. You can choose to leave this blank for password-less login, although it is recommended to have a passphrase if security is a concern.

2. Copy the Public Key to the Remote Server

Copy the public key (id_rsa.pub) to the remote server’s authorized keys file.

ssh-copy-id user@remote_host

This command will add your public key to the ~/.ssh/authorized_keys file on the remote server.

3. Verify SSH Key-Based Login

Try to log in to the remote server without a password:

ssh user@remote_host

If everything was set up correctly, you should be logged in without being prompted for a password.

4. Additional Security (Optional)

  • Disable Password Authentication: You can further secure your SSH access by disabling password authentication entirely. To do this, edit the SSH configuration file on the remote server:

    sudo nano /etc/ssh/sshd_config

    Find the line:

    PasswordAuthentication yes

    Change it to:

    PasswordAuthentication no

    Save the file and then restart the SSH service:

    sudo systemctl restart sshd
  • Use Passphrases: If you opted for a passphrase when generating your key, you’ll need to enter it the first time you use the key. To avoid entering it repeatedly, consider using an SSH agent to cache the passphrase.

Note

  1. Multiple Keys: If you have multiple keys or use different keys for different servers, you may need to specify which key to use in your SSH command using the -i option:

    ssh -i /path/to/private_key user@remote_host
  2. Permissions: Ensure your ~/.ssh/authorized_keys file and the ~/.ssh directory on the remote server have the correct permissions (700 for .ssh and 600 for authorized_keys).

By following these steps, you can set up SSH public key authentication and avoid typing your password for each session.