How to secure SSH on a Linux VPS
A public VPS receives automated login attempts within minutes of going online. These steps make SSH much harder to attack. They are written for Ubuntu or Debian; if you have not created a server yet, you can rent a Linux VPS and start from a clean image. Keep your current SSH session open until you have tested the new settings from a second window.
1. Create a normal user with sudo
adduser deploy
usermod -aG sudo deploy2. Use SSH keys instead of passwords
On your own computer:
ssh-keygen -t ed25519 -C "you@example.com"
ssh-copy-id deploy@YOUR_SERVER_IP
ssh deploy@YOUR_SERVER_IPLog in once with the key to confirm it works before you turn passwords off.
3. Turn off password and root login
Create /etc/ssh/sshd_config.d/99-hardening.conf:
PasswordAuthentication no
PermitRootLogin no
PubkeyAuthentication yes
MaxAuthTries 3Check the syntax and reload the service. The service is called ssh on Ubuntu and Debian and sshd on RHEL-based systems:
sudo sshd -t && sudo systemctl reload sshOpen a second terminal and log in again. Only then close the old session.
4. Enable a firewall
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status verboseOpen only the ports you need, such as 80 and 443 for a web server. You can also restrict SSH to your own IP address with a firewall rule in the cloud console.
5. Block repeated failures with Fail2ban
sudo apt install -y fail2banCreate /etc/fail2ban/jail.local:
[sshd]
enabled = true
maxretry = 5
findtime = 10m
bantime = 1hsudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd6. Install security updates automatically
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure --priority=low unattended-upgrades7. Optional extras
- Changing the SSH port reduces log noise but is not a security measure by itself.
- Protect the private key with a passphrase and keep a backup in a safe place.
- Review logins with
lastandsudo journalctl -u ssh --since today. - Take a snapshot once the server is configured, so you can restore a clean baseline.
If you are locked out, use the browser console in your cloud panel to log in and fix the configuration. Our DDoS protection guide covers the next layer of defence.
Frequently asked questions
Is it safe to disable root login?
Yes, if you first create a sudo user and test that its key works. You can still run administrative commands with sudo.
Do I need Fail2ban if I use keys only?
It is optional. With password login disabled, brute force cannot succeed, but Fail2ban reduces log noise and load.
What if I lose my SSH key?
Use the console in your cloud panel to log in, add a new public key to ~/.ssh/authorized_keys and remove the old one.