Setting up SSH key authentication on a Linux server involves generating a key pair on your local machine, copying the public key to the server, and ensuring the SSH configuration allows key-based authentication. Here’s a step-by-step guide:
Step 1: Generate an SSH Key Pair
- Open a terminal on your local machine.
- Generate the key pair using the
ssh-keygen
command:
``
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
``
-t rsa
: Specifies the type of key to create (RSA).-b 4096
: Specifies the number of bits in the key (4096 bits is a strong key size).-C "your_email@example.com"
: Adds a label to the key, such as your email address.
- When prompted, choose a location to save the key (the default is usually
~/.ssh/id_rsa
). - Optionally, enter a passphrase to add an extra layer of security.
Step 2: Copy the Public Key to the Server
- Use the
ssh-copy-id
command to copy your public key to the server:
ssh-copy-id username@server_ip_address
- Replace
username
with your username on the server. - Replace
server_ip_address
with the IP address or domain name of the server.
If ssh-copy-id
is not available, you can manually copy the key:
Step 3: Verify SSH Key Authentication
- Attempt to log in to the server using SSH:
ssh username@server_ip_address
You should be able to log in without being prompted for a password (unless you set a passphrase for the key).
Step 4: Configure SSH for Security (Optional but Recommended)
- Edit the SSH daemon configuration file on the server:
sudo nano /etc/ssh/sshd_config
- Ensure the following settings are configured:
PubkeyAuthentication yes
PasswordAuthentication no
ChallengeResponseAuthentication no
UsePAM no
PubkeyAuthentication yes
: Enables public key authentication.PasswordAuthentication no
: Disables password authentication for additional security.ChallengeResponseAuthentication no
: Disables challenge-response authentication.UsePAM no
: Disables Pluggable Authentication Modules (PAM).
- Restart the SSH service to apply the changes:
sudo systemctl restart ssh
Summary
- Generate an SSH key pair.
- Copy the public key to the server.
- Verify SSH key authentication.
- Optionally, configure the SSH daemon for enhanced security.
With these steps, you’ve set up SSH key authentication on your Linux server, improving both security and convenience.