SSH Agent Forwarding in Windows

SSH Agent Forwarding in Windows

Normal usage of SSH Agent

Starting an agent

If a command-line is given, this is executed as a sub-process of the agent. When the command dies, so does the agent.

In Linux, execute ssh-agent and immediately set environment variables (SSH_AUTH_SOCK, SSH_AGENT_PID) that are needed:

eval `ssh-agent` 

In Windows, the same effect is more complicated. We need to somehow transform output to set these two environment variables. This is tested solution:

set SSH_AUTH_SOCK=%TEMP%\ssh-agent.socket
rm -f %SSH_AUTH_SOCK%
FOR /F "tokens=1 delims=;" %r IN ('ssh-agent -a %SSH_AUTH_SOCK% ') DO @(SET %r >NUL 2>&1)
setx SSH_AUTH_SOCK %SSH_AUTH_SOCK%

Note: I used to use random unique temporary file as socket filename (ssh-agent.%RANDOM%-%TIME:~6,5%.ssh-socket). But in this case, it’s important that we have known SSH_AUTH_SOCK variable as we need that variable in every shell that we open. So this variable should be permanent.

Now, we have an active ssh-agent running in memory, and two important environment variables set accordingly.

Stopping an ssh-agent

We can kill the ssh-agent process anytime, with -k switch. It will kill the process based on variable SSH_AGENT_PID. It will fail if that variable is not properly set, and this will very often happen when we are switching CMD shell’s.

ssh-agent -k

So, when we don’t have a process PID in variable, and if we think that some agent process is still running wild, without the reason, in Windows we can kill them all with:

taskkill /im "ssh-agent.exe" /f

And, this is a simple and effective solution.

Adding identities to agent

Agent initially does not have any private keys. Keys are added using ssh-add command. Simply invoking this command without arguments will add a default ~/.ssh/id_rsa key to an agent.

To add another, specific key:

ssh-add ~/.ssh/michfield_rsa

List identities

To show the identities currently held by the running agent, type:

ssh-add -l

More

Great PowerShell helpers:
ssh-agent-utils.ps1

SSH Agent in Linux

# Start ssh-agent if it is not already running and set up ssh-agent variables
if [ "x" == "x`ps -x -u ${USER} | egrep [s]sh-agent`" ] ; then
  # no ssh-agent running"
  ssh-agent | sed -e "/^echo/d" > ${HOME}/.agent-env
  ssh-add ~/.ssh/id_rsa
fi
source ${HOME}/.agent-env

dotfiles/.bashrc at master · watsoncj/dotfiles · GitHub

date 01. Jun 2013 | modified 29. Dec 2023
filename: SSH Using ssh-agent