Set Up SSH Key Authentication on Linux (Step-by-Step Guide)

SSH key authentication is a convenient and secure way to log in to a Linux system. In this guide, you'll learn how to create a user, generate SSH keys, and configure a Linux server for passwordless SSH access.

Create a New User

If you haven't already created the user that will access the server, run:

sudo adduser newuser

Replace newuser with your preferred username.

Switch to the New User

Log in as the newly created user:

sudo su - newuser

This ensures all SSH files are created in the correct home directory.

Create the SSH Directory

Create the .ssh directory inside the user's home folder:

mkdir -p ~/.ssh

Set the Correct Permissions

SSH is very particular about file permissions. Incorrect permissions can prevent key authentication from working.

The required permissions are:

  • .ssh directory: 700
  • authorized_keys file: 600

Run the following commands:

chmod 700 ~/.ssh touch ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys

Generate an SSH Key Pair

On your local machine (not on the Linux server), generate a new SSH key pair:

ssh-keygen -t rsa -b 4096 -f ~/.ssh/newuser_key

This creates:

  • Private key: newuser_key
  • Public key: newuser_key.pub

Important: Never share your private key.

Copy the Public Key to the Server

Transfer the public key to the server:

scp ~/.ssh/newuser_key.pub newuser@your_server_ip:~/.ssh/

Append it to the authorized_keys file:

ssh newuser@your_server_ip "cat ~/.ssh/newuser_key.pub >> ~/.ssh/authorized_keys && rm ~/.ssh/newuser_key.pub"

This authorizes the key for future logins.

After copying the key, verify the permissions and ownership:

chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys chown -R newuser:newuser ~/.ssh

Connect Using the SSH Key

You can now connect to the server using your private key:

ssh -i ~/.ssh/newuser_key newuser@your_server_ip

Replace your_server_ip with your server's IP address or hostname.

If everything is configured correctly, you'll be logged in without being prompted for a password.

#linux

0 Comments