Ubuntu – Share first ssh connection to user@host opportunisitically using ControlMaster

ssh

I see from the ssh_config man page that you can share connections to host@user using ControlPath and ControlMaster.
Is there any way to do this opportunistically for each combination of local user, remote user, and remote host? So that the first connection to testuser@remotelaptop is shared when you ssh into it the second time and the first is still running?

(I use ssh keys. I'm not sure if that would make it easier or harder).

Best Answer

From the ssh_config man page:

ControlMaster
    ...
    Two additional options allow for opportunistic multiplexing: try
    to use a master connection but fall back to creating a new one if
    one does not already exist.  These options are: “auto” and
    “autoask”.  The latter requires confirmation like the “ask”
    option.

So if you configure ssh with ControlMaster auto, it will attempt to connect to use an existing SSH session, falling back to creating a new master connection if that fails.

So a configuration like the following is probably what you're after:

ControlMaster auto
ControlPath ~/.ssh/control/%r@%h:%p