SINT - BASH script for ssh-agent session management in Cygwin

In .bashrc:
if [ -f "$HOME/.bash_sshagent" ]; then
        . "$HOME/.bash_sshagent"
fi
 

preparations:
mkdir "$HOME/tmp/ssh-agent" && chmod go-rwx -R "$HOME/tmp/ssh-agent"


.bash_sshagent (updated @ 2013-10-23)
# ssh-agent
SSH_AUTH_SOCK="$HOME/tmp/ssh-agent/sock"
SSH_AGENT_VARS="$HOME/tmp/ssh-agent/vars"
 
if ! [ -S "$SSH_AUTH_SOCK" ]; then
    ssh-agent -a "$SSH_AUTH_SOCK" -s > "$SSH_AGENT_VARS"
else
    if [ -z "$(ps | awk '/ssh-agent/ {print $1}')" ]; then
        rm "$SSH_AUTH_SOCK"
        ssh-agent -a "$SSH_AUTH_SOCK" -s > "$SSH_AGENT_VARS"
    fi
fi
 
eval `cat "$SSH_AGENT_VARS"` > /dev/null
 


.bash_sshagent (old @ 2012-04-10)
# ssh-agent
SSH_AUTH_SOCK="$HOME/tmp/ssh-agent/sock"
if ! [ -S "$SSH_AUTH_SOCK" ]; then
        eval `ssh-agent -a $SSH_AUTH_SOCK`
else
        if [ "$(ps | grep "ssh-agent" | wc -l)" -eq "0" ]; then
                rm "$SSH_AUTH_SOCK"
                eval `ssh-agent -a $SSH_AUTH_SOCK`
        fi
        SSH_AGENT_PID=$(ps | grep ssh-agent | head -n 1 | awk '{ print $1 }')
        export SSH_AUTH_SOCK
        export SSH_AGENT_PID
fi
 

Description
This is how I configured SSH keys management with ssh-agent in Cygwin environment (installed into Microsoft Windows 7).

At first it will check if file defined by variable $SSH_AUTH_SOCK exists and if is it socket.  If is that true it will try to determine ssh-agent process ID (PID) and it will export it as $SSH_AGENT_PID with $SSH_AUTH_SOCK variable.

$SSH_AUTH_SOCK variable is always set to "$HOME/tmp/ssh-agent/sock" and ssh-agent is forced by -a parameter to create socket always at same place (set in $SSH_AUTH_SOCK).

If ssh-agent isn't running it will start a new instance.

If multiple instances of ssh-agent are running it will get PID only of first one script gets. The best way how to handle this situation is to kill all ssh-agent instances. Then new bash instance will start the new instance of ssh-agent for you.

author: niekto@niekde.sk (Jaroslav Petráš)

date: Fri, 20 Apr 2012 07:14:02 +0000

link: CyberAsylum.eu/sint-bash-script-for-sshagent-session-management-in-cygwin