Reusing an existing SSH connection for subsequent connects

From BNL Physics Computing

Reusing an established SSH connection

Recent OpenSSH provides a "master" mode which allows a connection to be shared by subsequent ones. It can be accessed via the command line or for commonly used servers it can be set up more conveniently in the .ssh/config file. This can be handy for users of CryptoCard as it lessens the fumbling about with the hardware token.

Command line

Start the master:

 user@home> ssh -M -S ~/.ssh/gateway.socket user@gateway

This will give you an otherwise normal connection. Subsequent connections can make use of this established one by doing the same command w/out the -M:

 user@home> ssh -S ~/.ssh/gateway.socket gateway

Note when the SSH client subsequently uses the socket it doesn't care what the target user@host is. You can send commands to the master like:

 user@home> ssh -S ~/.ssh/gateway.socket -O check foo 
 Master running (pid=18247)
 user@home> ssh -S ~/.ssh/gateway.socket -O exit foo 
 Exit request sent.

The exit command will terminate the master and any subsequent connections.

Automating mastermode

This requires OpenSSH 4.2 or later. You can automate the use of sockets by adding the following to ~/.ssh/config.

 Host *
   ControlMaster auto
   ControlPath ~/.ssh/sockets/%r@%h:%p

You will need to first make the directory:

 user@home> mkdir ~/.ssh/sockets

Then, just log in everywhere as normal. The sockets will be used automatically.

If you do not have OpenSSH 4.2, you can still specify a ControlPath but it must be explicit for each host and ControlMaster must be yes