Managing ssh-agent automatically (with cygwin/PuTTY-Support)

1 Apr

When using SSH with public keys it is very annoying to enter the pass phrase everytime you connect to a host. In some cases (I won’t talk about security here, but you should really check waht it means to use an SSH agent) you can use a SSH agent to store your private keys. I’ll show a little script here, wich I include in my .zprofile to reuse a running SSH agent or to start a new one in the case that no agent is running. This allows to share one single instance between all shell sessions.

First we define a little helper function in .zprofile (if you’re using bash instead of zsh, you have to edit .bash_profile instead):

This helps us to identify, which programms are installed.

First we check if ssh-agent is installed on our system (line 1). If this is the case, we check if SSH_AUTH_SOCKET isn’t already set (line 2; this is the case if we are connected via SSH and agent forwarding). If we don’t have an agent, we take a look at .agent.env: if it does not exist (lines 11-12) we can start an agent and save it’s PID in .agent.env to allow other shells to reuse the agent. If the file is already there we check if the referenced agent is still running (line 6). If it is, we reuse it, otherwise we start a new one (line 7-8):

So far, after parsing the .zprofile file, we have a running ssh-agent in every case. We can now execute ssh-add and add our key(s). On Windows, if using cygwin, the chance is high that you’re using pageant as your ssh-agent. pageant is the SSH agent that comes with PuTTY or WinSCP. However, there are some wrappers that allows openssh to authenticate with PuTTY’s pageant. One of these solutions is ssh-pageant. It is easyly installed:

The startup code looks nearly the same. I’ll show a univeral version here which works on all environments:

On linux, is also possible to kill the agent if the last user logs out:

Have more fun using SSH smiley

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.