Using SSH agent to manage keys
SSH agent is a background process that holds your decrypted SSH keys in memory, so you don’t need to enter your passphrase repeatedly.
How it works
- Start the agent (usually automatic in modern shells):
eval "$(ssh-agent -s)"- Add your key once (prompts for passphrase):
ssh-add ~/.ssh/id_ed25519# Enter passphrase once- Use SSH without entering passphrase:
ssh user@hostname # Agent automatically provides the keyssh user2@host2 # Still no passphrase needed- Agent forgets the key when you logout → automatic cleanup
Key commands
ssh-agent -s # Start agent and output shell commandsssh-add ~/.ssh/id_ed25519 # Add key (prompts for passphrase)ssh-add -l # List all loaded keysssh-add ~/.ssh/id_rsa # Add another keyssh-add -d ~/.ssh/id_ed25519 # Remove specific keyssh-add -D # Remove all keysWhy use SSH agent?
| Method | Passphrase needed? | Visible in history? | Security |
|---|---|---|---|
| Direct SSH | Every connection | ❌ | Good |
| SSH agent | Once per session | ❌ | Excellent (recommended) |
| sshpass | No (stored in command) | ⚠️ Yes | Poor |
| Unencrypted key | No | ❌ | Very poor |
Check if agent is running
echo $SSH_AUTH_SOCK# If output is empty, agent not runningAutomatic setup in ~/.zprofile or ~/.bash_profile
For convenience, add to your shell profile:
if [ -z "$SSH_AUTH_SOCK" ]; then eval "$(ssh-agent -s)"fissh-add ~/.ssh/id_ed25519 2>/dev/nullThis starts the agent automatically and loads your key on login (you’ll be prompted for the passphrase once).