SSH Agent Setup on Windows with cygwin
I've created this question just as a reminder for me since I usually do the setup of an SSH agent only once every few years.
So, how can one setup an SSH agent under Windows, assuming the usage of a linux-like shell enviroment?
My current setup:
- Windows 10 Pro
- should also work with older windows versions that provide the setx command (Win7)
-
Babun shell (zsh)
- is based on cygwin
What I've done:
I decided to add the startup commands to the file .zshrc so that it is run every time I startup a new shell. So here are the commands:
# startup of the ssh-agent
AGENT_PID=$(pgrep -x ssh-agent)
if [ $? -ne 0 ]; then
echo "~/.zshrc: Starting SSH Agent!"
eval `ssh-agent` && ssh-add ~/.ssh/id_rsa
setx SSH_AUTH_SOCK $SSH_AUTH_SOCK
setx SSH_AGENT_PID $SSH_AGENT_PID
echo "~/.zshrc: SSH Agent running (PID: $SSH_AGENT_PID)"
else
echo "~/.zshrc: SSH Agent already running (PID: $AGENT_PID)"
fi
- The pgrep command searches for running SSH agents. If one is running it will output the process id and skip the startup of another agent.
- If none could be found the agent is started and the enviroment variables are exported
-
eval `ssh-agent`
starts the agent and evaluates its output which is setting the environment variablesSSH_AUTH_SOCK
andSSH_AGENT_PID
-
ssh-add
adds the specified private key to the agent which will prompt for the private key passphrase initially. - Since the above mentioned variables are only set for the started shell process it is necessary to set them globally for the user to be available for other shells and other tools not started from the shell. This can be done using the setx command from Windows. I simply set the variables according to the ones retrieved from the agent.
-
After that you're all set and the agent is running and usable as soon as you first started a shell. To be sure that the agent launches with Windows startup you could also add the shell launcher to the Windows autostart.