0

I'm making a script that occasionally sends commands to another machine over ssh. At the moment, im just calling this one function that opens up a new shell for each command it sends like so:

 #!/bin/bash

port='22'
user='user'
host='hostname'

send_ssh() {
        ssh -oBatchMode=yes -oConnectTimeout=5 -p "$1" -tq "$2"@"$3" "$4" || exit 1
}

send_ssh "$port" "$user" "$host" true
   # it worked so do some stuff locally blah blah

send_ssh "$port" "$user" "$host" anothercommand
   # rest of script

I've looked at keeping a tunnel open in the background and / or using a control socket so i can speed things up without having to open a new connection for each command but cant work out if and wether it's worth doing that in this case.

1 Answer 1

1

Setting up a control socket is so easy that I would argue it is absolutely worth doing, even with only two calls to send_ssh.

send_ssh() {
    ssh -o ControlMaster=auto -o ControlPersist=10 -oBatchMode=yes -oConnectTimeout=5 -p "$1" -tq "$2"@"$3" "$4" || exit 1
}

ControlMaster=auto means that an existing connection will be used if available, otherwise one will be opened for you.

The setting ControlPersist=10 means that the connection to the remote host will remain open for 10 seconds after the client exists, you can adjust this as desired. You can set it to 0 or yes to keep it open permanently, in which case you'll want to make sure something like

ssh -o exit -p "$1" "$2@$3"

executes before your script exits to close the master connection.

Sign up to request clarification or add additional context in comments.

2 Comments

I think it's cautious to set ControlPath with ControlPersist set to 0.
That's probably a good idea regardless of the value of ControlPersist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.