Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

bash - What's the best way to send multiple commands via ssh whilst running a script?

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.

question from:https://stackoverflow.com/questions/65921621/whats-the-best-way-to-send-multiple-commands-via-ssh-whilst-running-a-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...