Allow multiple SSH sessions over an existing connection

share-2

Enabling SSH connection sharing allows you to reuse an existing ssh connection thus saving resources and removing the need to enter a password. Here, we'll run you through setting it up. We'll also mention a few pitfalls to watch out for.

Reading time:
2 min

SSH connection sharing

The first ssh connection to a box (the master connection) will ask for a password (unless you've set up a key pair).

All subsequent connections to the same box as that user (slave connections) will be multiplexed through the existing connection as shown in the diagram below.

Configuring SSH connection sharing

The SSH client settings are configured in /etc/ssh/ssh_config. If you wish to configure on a per user basis, ~/.ssh/config will need to be created for that user. Any options found in ~/.ssh/config override the general settings in /etc/ssh/ssh_config. Additionally, any options passed on the command line will override all of the above. In this example, we'll set up connection sharing for a particular user, so edit ~/.ssh/config for that user and add:

ControlMaster auto
ControlPath /tmp/ssh_control_socket_%h_%p_%r

Now following the first connection to a box, you'll notice subsequent connections will start much faster and will not require a password.

This benefits scp, sftp, rsync, sshfs and any other programs that use ssh for their underlying connection.

Stale sockets

If the client box is turned off unexpectedly (for example power failure) the control socket will get left in place. In this case connections to the other box will fail until the control socket is deleted.

Master connection lifetime

Note that the initial master connection will hang around until slave sessions using the connection have finished.

New connections without Control socket

While there is a master connection, if you change any client connection options (even if supplied on command line), they will not take effect. This is because the master connection is already established and slave sessions are just reusing that connection. To cause a new ssh session to create a fresh connection (thus allowing any new options to be used), use -S none for example:

ssh -S none 192.168.0.7

Thank you for reading this article.
Please share if you liked it.