Chapter 1 · Lesson 2 of 19
Server basics

Log in to a server with SSH keys

An SSH key pair lets you log in to a server by proving you hold a private key, which is safer than a password.

By the end you will

Create an SSH key pair, install the public key on your server and log in without a password.

Time
14 min
Level
Beginner
Check
4 questions
You need
  • A server you can reach over SSH with a password
  • A terminal on macOS or Linux

Passwords on a public server get guessed. Within minutes of a server going online, bots try common usernames and passwords against port 22. An SSH key replaces the password with something a bot cannot guess, and it saves you typing it every time. If you only do one thing to secure a new server, do this.

How it works#

A key pair is two files made together by a mathematical process. The private key stays on your computer. The public key can be copied anywhere. Data signed with the private key can be checked with the public key, but the public key cannot be used to work out the private one.

When you connect, the server looks up your public key in ~/.ssh/authorized_keys for the user you are logging in as. It then sends a challenge. Your ssh client signs it with the private key and sends back the signature. If the signature matches, you are in. The private key never crosses the network, and no password is sent.

Two details matter later. First, the key belongs to a user account: a key in root’s authorized_keys lets you in as root only. Second, sshd is strict about permissions. If your home folder, .ssh or authorized_keys can be written by other users, sshd ignores the key and falls back to a password.

A passphrase on the private key is a second lock. If someone copies your key file, they still need the passphrase. Your ssh agent can remember it for a session so you do not retype it.

A worked example from start to finish: you run ssh-keygen, which writes id_ed25519 and id_ed25519.pub. You run ssh-copy-id, which logs in with the password, creates ~/.ssh on the server if needed and appends the line from the .pub file to authorized_keys. You then run ssh: the client offers the public key, the server finds it in authorized_keys, sends a challenge, the client signs it and the server verifies the signature. You land in a shell. If any step fails, the server falls back to a password, unless you have turned passwords off.

Step 1: Create a key pair#

On your own computer run:

bash
ssh-keygen -t ed25519 -C "you@example.com"

-t ed25519 picks a modern, short and fast key type. -C adds a comment so you can tell keys apart later. Press Enter to accept the default location. Set a passphrase when asked.

What you should see: the prompt Enter file in which to save the key, then your key fingerprint and a small ASCII picture. This creates two files in ~/.ssh/: id_ed25519 (private, keep it secret) and id_ed25519.pub (public).

Step 2: Copy the public key to the server#

Replace 203.0.113.10 with your server’s IP address:

bash
ssh-copy-id root@203.0.113.10

You are asked for the server password once. The key is added to ~/.ssh/authorized_keys on the server.

What you should see: Number of key(s) added: 1, followed by a hint to try logging in. If the first connection asks Are you sure you want to continue connecting, compare the fingerprint with your provider’s console if you can, then answer yes.

Step 3: Log in#

bash
ssh root@203.0.113.10

What you should see: a shell with no password prompt, or only a prompt for your key passphrase. Add -v to the command if you want to watch which key is offered.

Step 4: Turn off password login#

Only do this after step 3 works, or you can lock yourself out. On the server edit /etc/ssh/sshd_config and set:

output
PasswordAuthentication no

The disable SSH password login lesson covers this in more depth. Then reload SSH:

bash
sudo systemctl reload ssh

reload re-reads the config without dropping your current session. Keep that session open and test a second login in a new terminal before you close it. On some distributions the service is called sshd, not ssh.

Check it worked#

Open a new terminal and run ssh root@203.0.113.10. You should be let in by key. To prove passwords are off, run this from your computer:

bash
ssh -o PubkeyAuthentication=no root@203.0.113.10

What you should see: Permission denied (publickey), with no password prompt. A machine without your key is refused the same way.

Edge cases and gotchas#

  • Permissions on the server decide whether the key works. If ~/.ssh is writable by group or others, or authorized_keys belongs to another user, sshd silently ignores the key. Fix with chmod 700 ~/.ssh, chmod 600 ~/.ssh/authorized_keys and chown -R user:user ~/.ssh.
  • The key is per user. Copying it to root does not let you log in as deploy. Install the key for each account you use.
  • Files in /etc/ssh/sshd_config.d/ can override your edit. On recent Ubuntu, a drop-in file may set PasswordAuthentication yes and win over the main file. Check with sudo sshd -T | grep -i passwordauthentication.
  • Too many keys in your agent can cause a refusal. The server limits attempts, so a client offering many keys may fail before the right one. Use ssh -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes to offer one.
  • Windows has its own tools. Recent Windows includes OpenSSH, and the same commands work in PowerShell, but ssh-copy-id is not included. Paste the contents of the .pub file into authorized_keys by hand.
  • A lost private key cannot be recovered. Nobody can regenerate it. Keep a backup in a password manager or an encrypted drive.
  • The first connection asks about an unknown host. The client saves the server fingerprint in ~/.ssh/known_hosts and checks it on later logins. Compare the fingerprint with the provider console when you can.
  • Root may accept keys but not passwords. Some images set PermitRootLogin prohibit-password, so ssh-copy-id root@... with a password fails. Use the key you gave the provider, or log in as the default user.
  • Very old servers may not know ed25519. If the server is old, generate an RSA key with ssh-keygen -t rsa -b 4096 instead.

Troubleshooting#

SymptomLikely causeFix
Permission denied (publickey)Key not installed for this user, or wrong key offeredRun ssh -v to see which keys are tried, then run ssh-copy-id for the right user
Still asks for a password after copying the keyLoose permissions on ~/.ssh or authorized_keysSet 700 on .ssh and 600 on authorized_keys, and fix the owner
Connection timed outWrong IP or a firewall blocking port 22Check the address and the firewall rules
WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!The server was rebuilt or you reached a different machineIf you rebuilt it, run ssh-keygen -R 203.0.113.10 and reconnect
Too many authentication failuresThe agent offered many keys firstUse -o IdentitiesOnly=yes -i with the right key
UNPROTECTED PRIVATE KEY FILE!The private key is readable by othersRun chmod 600 ~/.ssh/id_ed25519
ssh: connect to host 203.0.113.10 port 22: Connection refusedNothing listens on port 22Use the provider console to check the SSH service
Host key verification failed.The server fingerprint differs from known_hostsConfirm a rebuild, then run ssh-keygen -R 203.0.113.10

Real-world scenario#

Dana rents a server and logs in as root with the password from the provider email. She generates a key on her laptop, runs ssh-copy-id, and logs in without a password. Pleased, she sets PasswordAuthentication no and reloads SSH, but she closes her only session first.

The next login fails with Permission denied (publickey). It turns out a drop-in file in /etc/ssh/sshd_config.d/ was overriding the setting, and her key was in root’s file while she tried to log in as another user. She uses the provider’s web console to log in, fixes the owner of ~/.ssh, and tries again.

The lesson: change one thing, keep a second session open, test, and only then close the first.

Quick reference#

TaskCommand
Create a keyssh-keygen -t ed25519 -C "you@example.com"
Install the keyssh-copy-id user@203.0.113.10
Log in with one keyssh -i ~/.ssh/id_ed25519 user@203.0.113.10
Debug a loginssh -v user@203.0.113.10
Remove an old host entryssh-keygen -R 203.0.113.10

Security and safety notes#

  • Never share or upload the private key. If it leaks, remove its public half from every server.
  • Do not close your working session until a second login works with the new settings.
  • Keep a way in that does not need SSH, such as the provider’s web console.

Next#

Create a non-root sudo user.

Try it: Log in with a key

Create a key, copy it to the server and log in without a password.

practice, nothing runs on your machine

Want a real machine? Free browser labs: Killercoda

Check what you learned4 questions
1Which file must never leave your computer?
2Where does ssh-copy-id put the public key on the server?
3Why test a second login before turning off password login?
4Key login fails with Permission denied (publickey) and the key is in authorized_keys. What is a likely cause?

Frequently asked questions

Is it safe to share my public key?

Yes. The public key is meant to be shared. Never share the private key, the file without the .pub ending.

What if I lose my private key?

You lose that way in. Use your provider's console to log in, add a new public key, and remove the old one.

Do I need a different key for every server?

No. One key pair can open many servers, because each server only stores the public half. Use a separate key for work and personal use if you want to limit the damage of a leak.

Why does ssh still ask for a password after I copied my key?

Usually the permissions on the server's .ssh folder are too open, or the key went to a different user than you log in as. Check the Troubleshooting table below.

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios