TIL - Reuse your SSH connection

Posted by Marcus Folkesson on Monday, January 29, 2024

TIL - Reuse your SSH connection

TIL, Today I Learned, is more of a "I just figured this out: here are my notes, you may find them useful too" rather than a full blog post

OpenSSH has the feature to reuse an existing SSH connection for multiple subsequent connections to the same host. It will improve your workflow because it reduces the time it takes to establish a new connection and in cases where you have to type a password, the time saving is even more.

The feature is ControlMaster and is documented in ssh_config(5) [1]:

ControlMaster
Enables the sharing of multiple sessions over a single network connection.
When set to ''yes'', ssh(1) will listen for connections on a control
socket specified using the ControlPath argument.  Additional sessions
can connect to this socket using the same ControlPath with ControlMaster
set to ''no'' (the default).  These sessions will try to reuse the
master instance's network connection rather than initiating new ones,
but will fall back to connecting normally if the control socket does not
exist, or is not listening.

To make use of this feature add the following line to your ~./ssh/config file:

Host *
        ControlMaster auto
        ControlPath ~/.ssh/master-%r@%h:%p
        ControlPersist 4h

It will keep your connection for 4 hours.