Why use SSH keys?
-
SSH key pairs provide more secure authentication than passwords.
-
Only the private key (kept on your computer) can unlock access, while the public key (stored on the server) verifies your identity.
-
This prevents brute-force password attacks.
Setting up SSH keys
Generate a key pair on your computer:
ssh-keygen -t ed25519
Copy the public key to the server:
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server
If ssh-copy-id
is unavailable, manually append the public key to ~/.ssh/authorized_keys
on the server.
Test login:
ssh user@server
If successful, no password will be required.
Disabling password and root login
Once SSH key login is working, you can disable both password login and direct root login for better security.
Edit the SSH server configuration file:
sudo nano /etc/ssh/sshd_config
Enable public key authentication
PubkeyAuthentication yes
Disable password login and root login
PasswordAuthentication no
PermitRootLogin no
Save the file and restart the SSH service:
On RedHat/Fedora/CentOS
sudo systemctl restart sshd
On Debian/Ubuntu:
sudo systemctl restart ssh
(On older systems: sudo service ssh[d] restart
)
Now your server will:
-
Accept only SSH key authentication
-
Block root login over SSH