Return Home

Add SSH Key to Server for Secure Access 🔑

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"

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

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

  sudo systemctl status sshd
  PasswordAuthentication no
  PubkeyAuthentication yes
  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.

Written © 2024 Written Developer Tutorials and Posts.

𝕏