A Step-by-Step Guide to Setting Up SSH Key Authentication

Learn how to check for an existing SSH key, generate one if necessary, and securely copy it to your remote server for password-free authentication.

Banner

Setting up SSH key authentication ensures secure and password-free access to your remote server. Follow this step-by-step guide to check for an existing SSH key, generate one if needed, and copy it to your server.

1. Check for an Existing SSH Key

Run the following command to list files in the ~/.ssh directory:


ls -al ~/.ssh

A sample output may look like this:


total 32 drwx------ 2 root root 4096 Jan 9 15:22 .
drwx------ 8 root root 4096 Feb 28 13:21 .
-rw------- 1 root root 99 Jan 8 11:21
authorized_keys -rw-r--r-- 1 root root 62 Jan 9 15:22
config -rw------- 1 root root 3389 Jan 7 11:45
id_ed25519 -rw-r--r-- 1 root root 749 Jan 7 11:45
id_ed25519.pub -rw------- 1 root root 978 Jan 7 11:51
known_hosts -rw-r--r-- 1 root root 142 Jan 7 11:42
known_hosts.old

If you see id_ed25519 (or id_rsa for older RSA keys), you already have an SSH key. If no such file exists, proceed to generate a new one.

2. Generate a New SSH Key (if necessary)

To create a new SSH key, run:


ssh-keygen -t ed25519 -C "your_email@example.com"

Replace your_email@example.com with your actual email. When prompted:

Press [Enter] to save the key in the default location (~/.ssh/id_ed25519).
Optionally, set a passphrase for additional security.

3. Copy the Public Key to the Server

Now, transfer the public key to your remote server using:


ssh-copy-id -i ~/.ssh/id_ed25519.pub root@your-server-ip

Replace root@your-server-ip with your actual username and server IP address. This command ensures the public key is added to the server’s ~/.ssh/authorized_keys file.

4. Test the SSH Connection

Once the key is copied, test the connection:


ssh root@your-server-ip

If everything is set up correctly, you will log in without needing to enter a password (unless a passphrase was set for the SSH key).

Conclusion

Using SSH keys enhances security and streamlines server access. Now, you have a secure and efficient way to log in to your server without passwords!

A Step-by-Step Guide to Setting Up SSH Key Authentication | Software Engineer Blog