SSH Util Ruby Script

OpenSSH, that ships with Cygwin has a nice utility called ssh-agent. This program is a daemon that will hold on to your keys so that hosts you are authorized to log on to will not continually ask for your password. This is especially useful when working with CVS repositories over SSH. When you run ssh-agent, it spits out text that should be evaluated to set two environment variables that you will need in order to run ssh-add, to actually add your keys to it. That output looks like this:

export SSH_AUTH_SOCK;  
export SSH_AGENT_PID;  
echo Agent pid 1600;

On a Unix system, it’s easy to capture the output of ssh-agent and evaluate it, but under the ‘command shell’ that ships with Windows systems, which is so pathetically crippled that my old Commodore 64’s BASIC-based shell is looking pretty good, you can’t do that.

So what are those poor saps, myself included, who are using Windows systems to do? Ruby to the rescue. I wrote a simple script that executes ssh-agent, capturing the output, massaging it a little, and then creating a batch file that I can run to set the necessary variables. Simply redirecting the output to a batch file won’t work because there are some Unix-isms, such as exporting the variables, that don’t work on Windows. So, here’s the script:

lines = %x{ssh-agent}"c:/tmp/sde.bat", "w") do |file|   
  lines.each do |line|   
    chunks = line.chomp.split ';'   
    if chunks[0] =~ /^SSH/  
      file.puts "SET #{chunks[0]}"  

You can see that the script sends the captured and massaged output to a batch file called “sde.bat” located in C:/tmp. You can change both of these to suit your preference. Once the script runs, I simply execute the generated batch file and then run ssh-add. The nice thing about the generated batch file is that it lingers until the next time I run the Ruby script. Thus as I open new console Windows I can re-run it to get the environment variables set properly in each one.