Reputation: 59
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.
Upvotes: 0
Views: 182
Reputation: 532268
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.
Upvotes: 1