How to start and use ssh-agent as systemd service?

  1. How to start ssh-agent as systemd service? There are some suggestions in the net, but they are not complete.

  2. How to add automatically unencrypted keys if ssh-agent service was started successfully? Probably, adding keys from the list of ~/.ssh/.session-keys would be good.
  3. How to set SSH_AUTH_SOCK in any login session afterwards? The most correct way is to push it from ssh-agent service to systemd-logind service (have no idea if it’s ever possible). The plain naive way is just add it to /etc/profile.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

To create a systemd ssh-agent service, you need to create a file in ~/.config/systemd/user/ssh-agent.service because ssh-agent is user isolated.

Description=SSH key agent

ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK


Add SSH_AUTH_SOCK DEFAULT="${XDG_RUNTIME_DIR}/ssh-agent.socket" to ~/.pam_environment.

Finally enable and start this service.

systemctl --user enable ssh-agent
systemctl --user start ssh-agent

And, if you are using ssh version higher than 7.2. echo 'AddKeysToAgent yes' >> ~/.ssh/config

This will instruct the ssh client to always add the key to a running agent, so there’s no need to ssh-add it beforehand.

Note that when you create the ~/.ssh/config file you may need to run:

chmod 600 ~/.ssh/config
chown $USER ~/.ssh/config

Otherwise, you might receive the Bad owner or permissions on ~/.ssh/config error.

Method 2

This is not supported if you are using centos 7 because it will not support the --user flag of systemctl. See this centos bug report, Systemd User Support is Broken on Delivery

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x