1

I have adopted the following snippet from Visual Studio Code's documentaion to create an ssh-agent on login:

if [ -z "$SSH_AUTH_SOCK" ]; then
   # Check for a currently running instance of the agent
   RUNNING_AGENT="`ps -ax | grep 'ssh-agent -s' | grep -v grep | wc -l | tr -d '[:space:]'`"
   if [ "$RUNNING_AGENT" = "0" ]; then
        # Launch a new instance of the agent
        ssh-agent -s &> .ssh/ssh-agent
   fi
   eval `cat .ssh/ssh-agent`
fi

However, I see that on each login, a new ssh-agent is created when my ~/.zprofile is sourced, even if I have a few other sessions open.

While debugging the issue, I realized that a call to eval "$(ssh-agent -s)" creates the agent and prints its PID on the terminal. However, when I invoke ps, pgrep, htop, or similar commands, they do not show the ssh-agent process. If I rerun the same commands with sudo, I can find the process.

What can I do to make the ssh-agent process visible to the user who called it, so they can use the same agent in all their sessions?

Matt
  • 111
  • 4

1 Answers1

1

I have something similar that's much simpler using a user service.

[Unit]
Description=SSH Authentication Agent
Documentation=man:ssh-agent
Requires=run-user-%U.mount

[Service]
Type=exec
ExecStart=/usr/bin/ssh-agent -a %t/ssh-agent.sock -D
Restart=on-failure

RuntimeDirectory=ssh
RuntimeDirectoryMode=0700
KillMode=process
KillSignal=SIGTERM

[Install]
WantedBy=default.target

You just have to enable the service for the user (systemctl --user enable --now ssh-agent.service) and it will start with the first session. If you need to enable it for all users, use systemctl --global enable ssh-agent.service.

Add this to ~/.zprofile (or /etc/zsh/zprofile for all users):

# SSH_AGENT_PID isn't really necessary since it's mainly used to terminate the agent with `ssh-agent -k`
typeset -x SSH_AGENT_PID="$( systemctl --user show --property=MainPID --value ssh-agent.service )"
typeset -x SSH_AUTH_SOCK="${XDG_RUNTIME_DIR}/ssh/ssh-agent.sock"
Ginnungagap
  • 2,595
  • 10
  • 13