Back to tutorials
Tutorial

Set Up SSH Keys And Disable Password Login On VPS

Disable SSH password login safely: set up SSH keys, test access, add rollback, and stop brute-force attempts on your VPS.

By Anurag Singh
Updated on Dec 01, 2026
Category: Tutorial
Share article
Set Up SSH Keys And Disable Password Login On VPS

SSH password logins attract nonstop brute-force attempts. The clean fix is to disable SSH password login and require keys instead.

Do this only after you confirm you can still get in if you fat-finger a config line.

This walkthrough takes you from “passwords enabled” to “keys only” on a real VPS. It includes checkpoints and a rollback option you can trust.

These steps work on Ubuntu 22.04/24.04 LTS, Debian 12, AlmaLinux 9/10, and Rocky Linux 9/10.

On production servers, schedule a quiet window. Keep one SSH session open until you’re finished.

Prerequisites and the “don’t lock yourself out” checklist

Before you touch sshd_config, make sure the safety net is in place:

  • You have console access (provider web console / IPMI / rescue mode) or you can revert a snapshot.
  • You can keep one SSH session open while testing a second session.
  • You know which user you log in as (root, ubuntu, debian, almalinux, etc.).
  • Your SSH server is OpenSSH (typical on Linux servers).

If you’re hardening a fresh server, snapshots make this low-risk.

A small HostMyCode VPS is enough for most web stacks.

Snapshot before you change anything.

Confirm your current SSH setup (port, users, and auth methods)

Start by checking what the daemon is actually using right now.

Don’t rely on what you think it’s using.

# On the server
sudo sshd -T | egrep -i 'port|passwordauthentication|pubkeyauthentication|permitrootlogin|kbdinteractiveauthentication'

Pay attention to these lines:

  • port 22 (or your custom port)
  • passwordauthentication yes (this is what you’ll turn off)
  • pubkeyauthentication yes (this must stay on)

Also confirm the service name and that it’s running:

# Ubuntu/Debian
sudo systemctl status ssh

# AlmaLinux/Rocky
sudo systemctl status sshd

If you’ve already changed ports or firewall rules, keep troubleshooting separate.

First, get key login working. Then lock down everything else.

Create a key pair on your laptop (recommended: ed25519)

Generate keys on your local machine, not on the server.

On Linux/macOS:

ssh-keygen -t ed25519 -a 64 -C "yourname@yourdomain" -f ~/.ssh/id_ed25519_vps
  • -a 64 increases KDF rounds, which makes stolen key files harder to crack.
  • Use a passphrase. If your laptop gets stolen, the passphrase buys you time.

On Windows, you can use PowerShell (OpenSSH) or PuTTYgen.

With PowerShell OpenSSH:

ssh-keygen -t ed25519 -a 64 -C "yourname@yourdomain" -f $env:USERPROFILE\.ssh\id_ed25519_vps

You should end up with two files: the private key and the matching .pub public key.

Install your public key on the VPS (two safe methods)

You have two solid choices.

Use ssh-copy-id if it’s available. If not, add the key manually.

Method A: ssh-copy-id (fastest)

# From your local machine
ssh-copy-id -i ~/.ssh/id_ed25519_vps.pub user@YOUR_SERVER_IP

If SSH runs on a non-standard port:

ssh-copy-id -i ~/.ssh/id_ed25519_vps.pub -p 2222 user@YOUR_SERVER_IP

Method B: manual authorized_keys (works everywhere)

Print the public key locally:

cat ~/.ssh/id_ed25519_vps.pub

Then on the server, as the target user:

mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
# paste the single-line public key, save and exit
chmod 600 ~/.ssh/authorized_keys

Common mistake: loose permissions.

If ~/.ssh or authorized_keys is too open, OpenSSH may ignore it.

The chmod lines above fix that.

Verify key-based login in a second SSH session (do this before any config changes)

Leave your current SSH session open.

In a second terminal, force key auth and confirm it works end-to-end.

# From your local machine
ssh -i ~/.ssh/id_ed25519_vps user@YOUR_SERVER_IP

If it doesn’t work, re-run with debug output:

ssh -vvv -i ~/.ssh/id_ed25519_vps user@YOUR_SERVER_IP

What success looks like: you log in without being asked for the account password.

You may still be prompted for the key passphrase.

If it fails, check logs on the server:

# Ubuntu/Debian
sudo journalctl -u ssh -n 120 --no-pager

# AlmaLinux/Rocky
sudo journalctl -u sshd -n 120 --no-pager

Also double-check the username you’re logging in as and where you installed the key.

The key must live under that user’s home directory, not root’s.

Optional but smart: create a fallback admin user before disabling passwords

Relying on a single account is how simple mistakes turn into long nights.

Create a second admin user with its own key.

Later, you can disable root SSH access without sweating it.

# On the server
sudo adduser opsadmin 2>/dev/null || sudo useradd -m opsadmin
sudo usermod -aG sudo opsadmin 2>/dev/null || sudo usermod -aG wheel opsadmin

Install your key for that user as well:

# From your local machine
ssh-copy-id -i ~/.ssh/id_ed25519_vps.pub opsadmin@YOUR_SERVER_IP

Test it:

ssh -i ~/.ssh/id_ed25519_vps opsadmin@YOUR_SERVER_IP

Harden sshd_config safely (drop-in file preferred)

On modern distributions, a drop-in file under /etc/ssh/sshd_config.d/ is the safest place to harden settings.

You avoid overwriting vendor defaults. Drop-ins also make audits and future changes cleaner.

First, confirm what sshd is reading:

sudo sshd -T | head

If the directory exists, use it:

ls -la /etc/ssh/sshd_config.d/ 2>/dev/null || echo "No drop-in dir; will edit main file"

Create a hardening drop-in

Create /etc/ssh/sshd_config.d/99-hostmycode-hardening.conf:

sudo nano /etc/ssh/sshd_config.d/99-hostmycode-hardening.conf

Paste the following (update AllowUsers to match your actual accounts):

# Require keys; stop password brute-force
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes

# Root logins are a common target. If you need root, use sudo.
PermitRootLogin no

# Optional: restrict which users can SSH
AllowUsers opsadmin yourmainuser

# Keep auth attempts reasonable
MaxAuthTries 4
LoginGraceTime 30

If you don’t have /etc/ssh/sshd_config.d/, add the same lines at the end of /etc/ssh/sshd_config instead:

sudo nano /etc/ssh/sshd_config

Common mistake: using AllowUsers and forgetting your own username.

If you enable it, be precise.

Validate the SSH config before restarting (this avoids instant lockouts)

Always validate syntax before you reload anything.

One typo is enough to stop sshd from starting.

sudo sshd -t

No output means the syntax is fine.

If you get an error, fix it before going дальше.

Reload SSH and test logins (key should work, password should fail)

Reload the service.

Reload is safer than restart because it keeps existing connections alive.

# Ubuntu/Debian
sudo systemctl reload ssh

# AlmaLinux/Rocky
sudo systemctl reload sshd

Now test in a fresh terminal from your local machine:

ssh -i ~/.ssh/id_ed25519_vps yourmainuser@YOUR_SERVER_IP

Next, prove that password auth is blocked.

This test intentionally disables keys:

ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no yourmainuser@YOUR_SERVER_IP

Expected result: permission denied, even if you type the correct account password.

Add a safe rollback path (two practical options)

Real life happens.

Your office IP changes, a laptop disappears, or you realize AllowUsers has a typo.

Pick a rollback method you can execute quickly.

Option 1: Provider console + emergency config edit (most reliable)

Know where your VPS console lives in the hosting panel.

If SSH breaks, log in via console. Move the hardening file out of the way, then restart SSH.

# On the server console
sudo mv /etc/ssh/sshd_config.d/99-hostmycode-hardening.conf /root/
sudo sshd -t && sudo systemctl restart ssh || sudo systemctl restart sshd

Option 2: Temporary second SSH port during migration (extra safety)

If you want extra margin, run SSH on two ports temporarily.

Keep the current port while you verify hardened settings on an alternate port.

This is especially useful on remote production systems.

Add a second port in the main config (OpenSSH reads Port directives early; using the primary file avoids surprises):

sudo nano /etc/ssh/sshd_config

Add or edit:

Port 22
Port 2222

Validate and reload:

sudo sshd -t
sudo systemctl reload ssh || sudo systemctl reload sshd

Allow the new port in your firewall (UFW example):

sudo ufw allow 2222/tcp
sudo ufw status

Test:

ssh -p 2222 -i ~/.ssh/id_ed25519_vps yourmainuser@YOUR_SERVER_IP

Once you’re confident, remove the extra port and close it in the firewall.

Make brute-force attacks less noisy: firewall + CrowdSec (optional)

Key-only SSH closes off password guessing, but scanners will still knock on the door.

A basic firewall reduces exposure.

An IPS can cut the log spam further.

Firewall basics (UFW or firewalld)

On Ubuntu/Debian with UFW:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw enable
sudo ufw status verbose

On AlmaLinux/Rocky with firewalld:

sudo systemctl enable --now firewalld
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

If you want adaptive blocking for repeat offenders, follow the HostMyCode guide: Install CrowdSec on Ubuntu VPS to block bruteforce.

It pairs well with key-only SSH.

You reduce scanning noise without falling back to passwords.

Operational tips: SSH agent, multiple keys, and team access

After you switch to keys, workflow is usually the hard part.

This shows up quickly when you manage multiple servers.

Don’t “solve” it by copying private keys onto random machines.

Use ssh-agent (so you type the passphrase once)

# On your local machine
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519_vps

After that, new SSH connections won’t prompt again until the agent is cleared.

Use per-user keys, not shared keys

On a team, each person should have their own key.

Add and remove their line in authorized_keys as access changes.

You’ll avoid the “one shared key leaked, rotate everything” scenario.

How to verify you’re actually protected

Don’t trust what’s written in a file.

Verify what the running daemon is enforcing.

  • Server-side: sudo sshd -T | grep -i passwordauthentication should return no.
  • Client-side: a password-only attempt should fail:
ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no yourmainuser@YOUR_SERVER_IP

Finally, make sure it survives a reboot:

sudo reboot
# reconnect after the server comes back
ssh -i ~/.ssh/id_ed25519_vps yourmainuser@YOUR_SERVER_IP

Common mistakes (and quick fixes)

  • Wrong key installed: you copied a different .pub than the private key you’re using. Fix: confirm fingerprints with ssh-keygen -lf ~/.ssh/id_ed25519_vps.pub.
  • Permissions too open: SSH ignores keys. Fix: chmod 700 ~/.ssh and chmod 600 ~/.ssh/authorized_keys.
  • Editing the wrong file: multiple includes. Fix: run sudo sshd -T to see effective settings.
  • Locked out by AllowUsers: typo or missing user. Fix: use console access, remove AllowUsers, reload.
  • SELinux blocks access (RHEL-based): uncommon for pure SSH keys, but can happen with non-standard home dirs. Check sudo ausearch -m avc -ts recent.

Related hardening you can do next (without turning this into a project)

After passwords are gone, a few small steps give you a lot of security for the effort:

Summary: key-only SSH with a rollback plan

You generated a strong key, installed it, and proved key-based access works.

Then you turned off password authentication.

That removes the most common SSH compromise path: credential guessing.

Once you add ssh-agent to your workflow, the day-to-day overhead stays low.

If you want this baseline hardening applied consistently across servers, managed VPS hosting can cost less than cleaning up a preventable incident.

If you’d rather run it yourself, a standard HostMyCode VPS gives you the access you need, plus snapshots and console options for safer changes.

On a production server, SSH is a front door. Treat it that way. If you want an environment where hardening is straightforward (snapshots, console access, predictable networking), start with a HostMyCode VPS. If you’d rather not spend your week on patching and security chores, managed VPS hosting keeps the basics tight and consistent.

FAQ

Will disabling SSH password login break SFTP or SCP?

No. SFTP and SCP use SSH authentication.

With keys in place, they keep working. They’ll just stop accepting account passwords.

Should I disable root SSH login too?

Yes for most servers. Set PermitRootLogin no, and use a normal user plus sudo.

Keep console access available for emergencies.

Do I need to change the SSH port if I disable passwords?

Not strictly. Key-only auth blocks password guessing.

Changing the port can reduce log noise, but it’s security through obscurity, not a primary control.

What if I lost my private key after disabling passwords?

Use your provider console/rescue mode to log in and add a new public key to ~/.ssh/authorized_keys.

Or temporarily re-enable PasswordAuthentication long enough to recover safely.

How do I confirm which SSH settings are actually active?

Run sudo sshd -T. It prints the effective configuration after includes, overrides, and defaults—much more reliable than eyeballing files.