How to Set Up a Persistent SSH Agent
If you regularly access your server or mini PC via SSH and find yourself typing your SSH key passphrase repeatedly, you’ll appreciate a solution that remembers your key for the entire user session. In this post, I’ll show you how to configure a persistent SSH agent managed by systemd --user
.
- Starts automatically at login or system boot
- Shares the SSH agent between multiple SSH sessions
- Only asks for your SSH key passphrase once per reboot
Why is this useful?
Without this setup, every new SSH session requires you to unlock your SSH key, which can become annoying if you frequently connect or open multiple terminals. A persistent ssh-agent
keeps your decrypted key in memory, so you authenticate just once.
Steps to Configure a Persistent ssh-agent
1. Create a systemd user service for ssh-agent
Create a directory and a service file:
mkdir -p ~/.config/systemd/user
nano ~/.config/systemd/user/ssh-agent.service
Paste the following content:
[Unit]
Description=SSH key agent
After=network.target
[Service]
Type=simple
Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK
[Install]
WantedBy=default.target
2. Enable linger for your user
This allows the user-level systemd
services to keep running without active sessions:
sudo loginctl enable-linger $(whoami)
3. Start and enable the ssh-agent service
Reload systemd user daemon and enable the service:
systemctl --user daemon-reexec
systemctl --user daemon-reload
systemctl --user enable --now ssh-agent.service
4. Configure your shell environment
Add this to your ~/.bashrc
or ~/.zshrc
:
export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"
ssh-add -l > /dev/null 2>&1 || ssh-add ~/.ssh/id_ed25519
This makes sure your sessions use the persistent agent and add your key only if not already loaded.
Summary
After these steps, your SSH agent will be managed by systemd, persist across SSH sessions, and you only need to enter your SSH key passphrase once after reboot. This setup improves your workflow and saves time when working with remote servers.