Ssh – Automatically spawn a ControlMaster background process on first access to a ssh remote system

ssh

Lately I'm often using the SSH client's ControlMaster feature, which allows me to use a single SSH-TCP-connection for multiple shells and port forwardings to the same remote system. The most annoying thing about this is, that the first shell's process that is opened becomes automatically the ControlMaster. That means, if this process gets terminated, all other shells and port forwardings using the control master connection become unavailable.

I would really like when the first ssh command to a remote system would spawn an additional background process which holds the connection as long as there are still connections using the ControlMaster connection, so I could simply close the actual shells whithout having to risk to crash other connections. Ideally the background ControlMaster process would even be configurable to wait for an amount of time for new shells or port forwardings to use the ControlMaster before finally shutting down.

Is there a way to make the ssh client do such a thing? I know I could create such a connection manually before using ssh to create the first shell, but I explicitly want this to happen automatically because otherwise I would surely forget to do it every now and then.

Letting a wrapper script do it also wouldn't be so easy because I often use configured shorthands for remote server names in .ssh/config and the ControlMaster socket is created using USERNAME@NETWORK_NAME:NETWORK_PORT as name. So a wrapper would need to understand .config/ssh perfectly to work as intended.

Best Answer

You should use the ControlPersist config option.

 ControlPersist
         When used in conjunction with ControlMaster, specifies that the
         master connection should remain open in the background (waiting
         for future client connections) after the initial client connec‐
         tion has been closed.  If set to “no”, then the master connection
         will not be placed into the background, and will close as soon as
         the initial client connection is closed.  If set to “yes”, then
         the master connection will remain in the background indefinitely
         (until killed or closed via a mechanism such as the ssh(1) “-O
         exit” option).  If set to a time in seconds, or a time in any of
         the formats documented in sshd_config(5), then the backgrounded
         master connection will automatically terminate after it has
         remained idle (with no client connections) for the specified
         time.

ControlPersist no is the default behaviour, which is as you describe. I use ControlPersist 4h to allow the background sessions to clean themselves up periodically.