Add SSH Key to Server for Secure Access 🔑

Last Modified: June 03, 2024

Introduction

Securely accessing your server via SSH is a critical skill for developers and system administrators. By adding an SSH key to your server, you can enhance security and streamline the login process. This guide will walk you through the steps to add an SSH key to your server, ensuring secure access for the intended user.

Step 1: Generate SSH Key Pair

Before adding an SSH key to the server, you need an SSH key pair. If you don't have one, follow these steps to generate it:

  1. Open your terminal.
  2. Run the following command:
   ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
  • Follow the prompts to save the key pair to the default location (~/.ssh/id_rsa and ~/.ssh/id_rsa.pub).
  • Optionally, add a passphrase for extra security.

Step 2: Copy the Public Key to the Server

There are a couple of methods to copy the public key to your server:

Method 1: Using ssh-copy-id

  1. Run the following command, replacing username and server_ip with the appropriate values:
   ssh-copy-id username@server_ip
  • This command prompts you for the user's password on the server.
  • It then copies your public key (~/.ssh/id_rsa.pub) to the server's ~/.ssh/authorized_keys file.

Method 2: Manually Copying the Key

  1. Display the contents of your public key file:
   cat ~/.ssh/id_rsa.pub
  1. Copy the output to your clipboard.
  2. SSH into the server:
   ssh username@server_ip
  1. Create the .ssh directory and authorized_keys file if they don't exist:
   mkdir -p ~/.ssh
   touch ~/.ssh/authorized_keys
   chmod 700 ~/.ssh
   chmod 600 ~/.ssh/authorized_keys
  1. Open the authorized_keys file in a text editor:
   nano ~/.ssh/authorized_keys
  1. Paste your public key into the file.
  2. Save and close the file (in Nano, press Ctrl+X, then Y, and Enter).

Step 3: Test SSH Access

From your local machine, test the SSH access:

ssh username@server_ip

If everything is set up correctly, you should log in without a password prompt.

Additional Tips

  • Ensure the sshd service is running on the server:
  sudo systemctl status sshd
  • Verify the server's SSH configuration (/etc/ssh/sshd_config) allows key-based authentication:
  PasswordAuthentication no
  PubkeyAuthentication yes
  • Restart the SSH service if you make configuration changes:
  sudo systemctl restart sshd

By following these steps, you can securely add an SSH key to your server, granting access to the intended user while maintaining high security standards.