Running multiple seperate commands via seperate SSH invocations can be very slow, so we sometimes want to multiplex SSH sessions over an existing connection (i.e. re-use the connection).
This can be particularly useful if you're shelling into a system which requires two-factor authentication as you'll only need to answer a challenge for the first connection.
It's also useful if you're using something like ansible
, as it can massively improve runbook speed.
# The original set of commands
# There's going to be 3 connections, handshakes etc and it'll be slow to run
ssh $dest "uname -r"
ssh $dest "docker ps -q | wc -l"
ssh $dest "ls /some/dir/ | wc -l"
# Instead, open a control connection
ssh -o controlmaster=auto -o controlpath=~/.ssh/.ssh-%r@%h:%p -N $dest &
# Get piddy mcpidface
control_pid=$!
# do the other SSH stuff as before, but give it the controlmaster details
ssh -o controlmaster=auto -o controlpath=~/.ssh/ssh-%r@%h:%p $dest "uname -r"
ssh -o controlmaster=auto -o controlpath=~/.ssh/.ssh-%r@%h:%p $dest "docker ps -q | wc -l"
ssh -o controlmaster=auto -o controlpath=~/.ssh/.ssh-%r@%h:%p $dest "ls /influxdb/meta/ | wc -l"
# Once we're done, tidy up the original connection
kill $control_pid
# Done
# -----------------------------
# If we wanted to make this behaviour the default
# put this into ~/.ssh/config
#
host *
controlmaster auto
controlpath ~/.ssh/.ssh-%r@%h:%p