Re-using SSH connections with controlmaster



Published: 2022-04-12 07:55:53 +0000
Categories: Misc,

Language

Misc

Description

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.

Snippet

# 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

Keywords

ssh, multiplex, reuse, connection, keep-alive,

Latest Posts


Copyright © 2022 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk, http://phecoopwm6x7azx26ctuqcp6673bbqkrqfeoiz2wwk36sady5tqbdpqd.onion and http://snippets.bentasker.i2p
hit counter