Skip to content. | Skip to navigation

Personal tools

Navigation

You are here: Home / Blog / Re-using SSH Connections

Re-using SSH Connections

by Ross Patterson last modified Jul 26, 2008 09:25 AM
Automatic master SSH connections for sharing and multiplexing

Yet again I've discovered that somethign I've been dreaming of forever already existed for just about that long.  :)

I use SSH for so many things these days that the startup time for connections really begins to add up.  Enter OpenSSH connection sharing.  See that blog post for details.  Also see this thread on the SVN development list for details of a workaround for an svn+ssh issue.

I was still left wanting, however.  The lion's share of the time I want to save re-using SSH connections is for svn+ssh.  The SVN workaround requires that I think enough ahead to start the master for every host I connect to.  I connect to a lot of hosts and they're constantly changing so I wanted something I didn't have to think about.  Also mildly annoying is the fact that the first SSH session to a host would become the master and couldn't be closed or killed without killing all slaves and, of course, killing the master.

I wrote a wrapper for SSH that would start the master in the background if need be and then run the ssh command as a normal slave.  This solution allows the individual connection to close or be killed without affecting the master.  It also obviates the need for the svn+ssh workaround.  Enjoy:

#!/bin/sh
## Wrapper script for ssh that backgrounds the control master if one
## isn't already started.

## the real ssh
SSH="/usr/bin/ssh"

## optstring assembled from `man ssh`
optstring="+1246AaCfgKkMNnqsTtVvXxYb:c:D:e:F:i:L:l:m:O:o:p:R:S:w:"
## get ssh options
opts=`getopt -- "$optstring" "$@"`

## the non-option args follow "--"
## convert to an array of IFS separated strings
args=(${opts#*--})

## the host is the first non-option arg
## use eval to process the quoted strings returned by getopt
host=`eval echo ${args[0]}`

## if the master isn't running, start it in the background
$SSH -q -O check $host 2>/dev/null || $SSH -MNf $host

## replace ourselves with the reall ssh call
exec $SSH "$@"
Navigation
OpenID Login

Contact

me@rpatterson.net

IRC: zenwryly@irc.freenode.net
plone.org: rossp
GTalk: mer@patterson.net
Yahoo IM: patterson_ross
AIM: rosspatters
MSN: me@rpatterson.net
Skype: merpattersonnet

PO Box 7775 #10587
San Francisco, CA
94120-7775

Phone
+1 (415) 894-5323