# SSH connection multiplexing

You ever frequently connect to the same SSH server to perform subsequent
commands? Maybe you `rsync` files to the server, then you just want to tell it
to restart a service, for example.

Regularly, every time you call `ssh`, it establishes a new connection. It does
so by sending a command to an SSH server to setup a new connection, and once the
command is carried out or the shell is exit, sends another command to
disconnect.

But, you can also tell SSH to not disconnect right away, and instead keep and
re-use the same connection for any subsequent commands you want to run. That's
called "connection multiplexing," and it's easy to set up. Saves up some time
from always handshaking and authenticating every time you want to do something
on the same server via SSH.

By the way, since it's for SSH, this also works with RSync via SSH!

Do yourself a favour and add the configuration lines below in
`~/.ssh/multiplexing.inc`:

```
# ~/.ssh/multiplexing.inc
ControlMaster auto
ControlPath ~/.ssh/cm-%r@%h:%p
ControlPersist 10m
```

Then, wherever you want to use connection multiplexing, maybe only your
favourite machines or all of them, include the file above:

```
# ~/.ssh/config

# Example host only
Host example.com
	Include ~/.ssh/multiplexing.inc
```

(You can also include the lines for `~/.ssh/multiplexing.inc` directly in
`~/.ssh/config`, if you want. The above is just a suggestion to help organise
the SSH config.)

The next time you connect to an SSH server with multiplexing set up, a socket
file will be created in `~/.ssh`. This will keep the connection open for up to
10 minutes after the last command. (Feel free to change the `ControlPersist 10m`
line to how long you want connections to remain.) In the case a connection
expires, or the socket file is missing, only then `ssh` will establish a new
connection.

You can also close the connection immediately, if you want:

```sh
ssh -O exit example.com
```

Enjoy the re-usability of the SSH connections!

---

_This article expands on the
[original tip I posted on X](https://x.com/remino/status/1829870270880034848)
back on <time>2024-08-31</time>._
