How to regenerate SSH server keys on Ubuntu?

This is the cleanest and most Ubuntu-appropriate method:

Restart the SSH service:

sudo systemctl restart ssh

Reconfigure OpenSSH server to regenerate keys:

sudo dpkg-reconfigure openssh-server

Remove existing host keys:

sudo rm /etc/ssh/ssh_host_*

Method 2: Manual key generation

If you prefer more control over the process:

Restart the SSH service:

sudo systemctl restart ssh

Verify the keys were created:

ls -la /etc/ssh/*key*

Generate new keys manually:

sudo ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -q -t rsa
sudo ssh-keygen -f /etc/ssh/ssh_host_ecdsa_key -N '' -q -t ecdsa
sudo ssh-keygen -f /etc/ssh/ssh_host_ed25519_key -N '' -q -t ed25519

Remove existing host keys:

sudo rm /etc/ssh/ssh_host_*

Method 3: Reinstall OpenSSH server

An alternative approach that will also regenerate keys:

sudo rm /etc/ssh/ssh_host_*
sudo apt reinstall openssh-server

Important Notes:

  • ⚠️ Warning: It's highly recommended to perform this operation from the console/physical access rather than over SSH, as you could lose your SSH connection if something goes wrong.
  • After regenerating keys, clients connecting to your server will see a host key mismatch warning and will need to remove the old key from their ~/.ssh/known_hosts file.
  • The new keys will be automatically used by the SSH daemon after the service restart.

When to regenerate SSH keys:

  • After cloning a VM or container
  • When you suspect the keys may have been compromised
  • When moving a system to a new network where the old keys should not be trusted
  • After a security incident