You are here: Home / Software / SSH Multiplex

SSH Multiplex

Guess you are already using ssh keys to make your remote logins. Now think about running a series of commands on a remote system. Normaly you would just execute them reading them from stdin, sending them as script or (worst) run them one by one.

ssh example.com "echo hello"; ssh example.com "echo world"
0.03s user 0.02s system 0% cpu 5.104 total

ssh example.com "echo hello; echo world"
0.02s user 0.01s system 2% cpu 1.407 total

Control Connections

With OpenSSH 4 there comes the new feature of a control connection. Establish one connection to the remote system. Keep this connection open all the time. The next connection will use this existing connection. Thus avoiding setting up a tcp connection. And avoiding to do an authentication handshake.

Bonus: The ControlMaster is a pure client side thing. No need to upgrade your server.

ssh -MNf example.com;
ssh example.com "echo hello"; ssh example.com "echo world";
ssh -O exit example.com
0.04s user 0.02s system 2% cpu 2.706 total

ok not as good as the just-one-long-line example. But what happens if we execute quite a bunch of stuff.

for i in {1..20}; do
        ssh example.com "echo $i";
done
0.32s user 0.07s system 0% cpu 57.666 total

using a multiplexed connection

ssh -MNf example.com
for i in {1..20}; do
        ssh example.com "echo $i";
done
ssh -O exit example.com
0.16s user 0.07s system 1% cpu 16.071 total

The examples are stupid, you could simply bunch all the echo requests in on command executing them on the remote system in a single connection. But imagine you have a script that does things step by step. First check something on the remote, then copy a file, than install it, then check again.

Or if you regularly use a remote system, add persistent connections to your login.

Automatic Master

You can configure your ssh to automatically create a ControlMaster on the first connection. But remember that the initial connection will only terminate if the last connection using this master ends.

cat ~/.ssh/config
Host *
ControlPath ~/.ssh/master%r@%h:%p
ControlMaster auto