Reusing existing OpenSSH v4 connections
Posted by Steve on Thu 10 Nov 2005 at 11:18
I've recently learnt of an interesting new features of OpenSSH v4 which allows you to reuse open connections when connecting to the same host more than once. If you regularly have multiple open connections to a single host this is a big timesaver.
This takes advantage of a new option "ControlMaster". Quoting from the manpage:
Enables the sharing of multiple sessions over a single network connection. When set to "yes" ssh will listen for connections on a control socket specified using the ControlPath argument.
Specify the path to the control socket used for connection sharing as described in the ControlMaster section above or the string "none" to disable connection sharing. In the path, '%h' will be substituted by the target host name, '%p' the port and '%r' by the remote login username. It is recommended that any ControlPath used for opportunistic connection sharing include all three of these escape sequences.
So what does this mean? It means that you can setup a socket in the path ControlPath, and this socket will be used when you reconnect to the given host.
An example will be clearer.
Assume that you're on the host itchy and you wish to connect multiple times to the host scratchy.
Connect the first time with :
ssh scratchy -M -S /tmp/%r@%h:%p
Here we've set two options:
This is setting the "ControlMaster" option.
- -S /tmp/%r@%h:%p
This is the setting for the ControlPath specifying that we should save the master socket as /tmp/user@hostname:port.
Now that we've setup the master connection we can connect a second time with:
ssh scratchy -S /tmp/%r@%h:%p
This time the connection is immediate. There is no option negotiation, etc, taking place. We can verify this by adding a -v flag:
skx@itchy:~$ ssh -v scratchy -S /tmp/%r@%h:%p OpenSSH_4.2p1 Debian-5, OpenSSL 0.9.8a 11 Oct 2005 debug1: Reading configuration data /home/skx/.ssh/config debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for * Linux scratchy.my.flat 2.6.8-1-386 #1 Thu Nov 25 04:24:08 UTC 2004 i686 GNU/Linux The programs included with the Debian GNU/Linux system are free software; ... ... snip
There we see the connection just occurs almost immediately, with none of the usual OpenSSH negotiation taking place.
Rather than messing around upon the command line we can setup these options within the configuration file .ssh/config, simply add a new stanza reading:
Host * ControlPath /tmp/%r@%h:%p
Now we can connect as normal, so long as we make the first connection to any host with -M (for "Master") all subsequent connections will be much faster.
If you don't think you can remember to specify the -M flag for the first one then you can also force this by setting your options to:
Host * ControlMaster auto ControlPath /tmp/%r@%h:%p
(Using autoask instead of auto will force the connection to prompt you whether you wish to setup a socket)