Follow this step-by-step guide to configure SSH key-based authentication on your Ubuntu server. Sign in securely without a password and optionally disable password authentication entirely.
Follow each step carefully to set up SSH key-based authentication on your Ubuntu 16.04 server.
Run the following command on your local machine to generate a 2048-bit RSA key pair (use -b 4096 for a stronger 4096-bit key):
$ ssh-keygen
When prompted for a file path, press Enter to accept the default (~/.ssh/id_rsa). Optionally set a passphrase for an extra layer of security.
Two files are created: ~/.ssh/id_rsa (private key — keep this secret) and ~/.ssh/id_rsa.pub (public key — this goes on the server).
Method 1 — ssh-copy-id (recommended):
$ ssh-copy-id username@remote_host
Enter your password when prompted. The public key will be appended to ~/.ssh/authorized_keys on the server.
Method 2 — via SSH pipe:
cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Method 3 — manually: Display your public key with cat ~/.ssh/id_rsa.pub, then append its output to ~/.ssh/authorized_keys on the remote server.
Test that key-based authentication works by connecting to your server:
$ ssh username@remote_host
If you set a passphrase in step 1, you will be prompted to enter it. If you did not, you will be logged in immediately without any password prompt.
Once you have confirmed key-based login works, you can disable password authentication to harden the server against brute-force attacks. Open the SSH daemon config:
sudo nano /etc/ssh/sshd_config
Find PasswordAuthentication, uncomment the line if needed, and set it to no:
PasswordAuthentication no
Save the file (Ctrl+X, then Y, then Enter) and restart SSH:
$ sudo systemctl restart ssh
Open a new terminal and verify you can still connect before closing your current session.
Common questions about setting up SSH key authentication on Ubuntu.