Sub topic 3
Using ssh-agent to Avoid Retyping Your Passphrase
This chapter assumes you have a key pair at ~/.ssh/id_ed25519 protected by a passphrase, that the public key is already installed on your server, and that you can run ssh from a Linux or macOS terminal.
Caching your key with ssh-agent
ssh-agent is a background program that holds decrypted private keys in memory. ssh-add loads a key into it, asking for the passphrase once.
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
ssh-add -lThe last command lists the fingerprints of loaded keys. Keys stay in the agent until you run ssh-add -D or the agent exits.
Simplifying connections with ~/.ssh/config
The client config file maps a short name to a host, user, and key.
Host myserver
HostName server.example.com
User alice
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yesNow ssh myserver replaces the longer command. IdentitiesOnly yes tells ssh to offer only the named key to this host, even when the agent holds others.
Troubleshooting when the key is not accepted
Start with verbose output. It shows each key offered and the server's reply.
ssh -v myserver 2>&1 | grep -iE "offering|denied|accepted"| Symptom | Likely cause | Fix |
|---|---|---|
| Key is never offered | Wrong `IdentityFile` path | Correct the path in `~/.ssh/config` |
| Permission denied | Public key missing from server | Reinstall the public key |
| Key rejected silently | Loose file permissions | Run `chmod 700 ~/.ssh` and `chmod 600 ~/.ssh/authorized_keys` |
On Debian and Ubuntu, read /var/log/auth.log on the server. On other systems, use journalctl -u sshd.
Disabling password logins on the server
After key login works, edit /etc/ssh/sshd_config:
PubkeyAuthentication yes
PasswordAuthentication no
KbdInteractiveAuthentication noThen check the syntax and reload the service:
sudo sshd -t && sudo systemctl reload sshd> Keep your current session open while you test. Log in from a second terminal before you close the first.
Managing multiple keys, rotation, and revocation
Use a separate key for each device. To rotate a key, generate a new pair, install its public key, test the login, and then delete the old line from ~/.ssh/authorized_keys. To revoke access, delete that line on every server that trusted the key.
Exercise
Why does IdentitiesOnly yes matter when several keys are loaded in ssh-agent?
Show answer
Without it, ssh offers each agent key in turn. Many failed offers can hit the server's MaxAuthTries limit and cause a rejection, so IdentitiesOnly limits the offer to the key you named.