Guides · Hardening · updated 3 Dec 2026
How to disable SSH password login and allow keys only (without locking yourself out)
Password guessing against SSH never stops. Keys only removes that attack completely. The risk is locking yourself out, so the order matters: prove the key works first, change the setting, test from a second terminal.
Prove key login works
From your own computer, in a new terminal, log in with the key. If this asks for a password, stop and fix it first.
ssh-copy-id user@SERVER_IP ssh -o PreferredAuthentications=publickey user@SERVER_IPFind where the setting is already defined
In OpenSSH the first value found wins, so a PasswordAuthentication yes earlier in the main file, or inside a Match block, overrides your new file.
sudo grep -rn 'PasswordAuthentication' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/Write the hardening file
A drop-in file whose name sorts first. Remove or edit any conflicting line the previous step found.
printf 'PasswordAuthentication no\nKbdInteractiveAuthentication no\nPermitRootLogin prohibit-password\n' | sudo tee /etc/ssh/sshd_config.d/00-hardening.confTest the configuration, then reload
sshd -t refuses to continue if the syntax is wrong. Reload keeps your current session. The service is called ssh on Debian and Ubuntu and sshd on RHEL.
sudo sshd -t && sudo systemctl reload ssh # RHEL: sshdConfirm the effective settings and test in a second terminal
Keep the first session open until the second works.
sudo sshd -T | grep -Ei 'passwordauthentication|permitrootlogin' ssh -o PubkeyAuthentication=no user@SERVER_IP # must be refused
Common mistakes
- Closing your only session before testing.
- Cloud images that ship a cloud-init file in sshd_config.d that sets PasswordAuthentication yes and sorts before yours.
- Forgetting root keys: if you disable passwords and root has no key, only users with keys can log in.
How to undo it
From the provider's web console, delete /etc/ssh/sshd_config.d/00-hardening.conf and run sudo systemctl reload ssh.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.