1

I would like to run several commands on one SSH session. For example, my script right now has something like the following:

ssh "machine A" do-thing-1
ssh "machine B" do-thing-2
ssh "machine A" do-thing-3

Having to SSH to A again in the third line is wasting a lot of time. How do I execute this without having to SSH again? Is this possible?

2
  • Is there any reason the code on machine B must run between thing 1 and thing 2 (that is, use ssh "machine A" "do-thing-1; do-thing-3"; ssh "machine B" do-thing 2). Otherwise, look at using the -M option when connecting to machine A so that the two logins to machine A can use the same socket (only the first needs to authenticate; the second can piggy-back over the original connection).
    – chepner
    Jul 2, 2015 at 3:25
  • 1
    Possible duplicate of What is the cleanest way to ssh and run multiple commands in Bash?
    – jww
    Aug 23, 2019 at 20:40

2 Answers 2

3

If the ssh to A does not consume its standard input, you can easily make it wait for input. Perhaps something like this.

ssh B 'sleep 5; do-thing-2; echo done.' | ssh A 'do-thing-1; read done; do-thing3'

The arbitrary sleep to allow do-thing-1 to happen first is obviously a wart and a potential race condition.

A somewhat simpler and more robust solution is to use the ControlMaster feature to create a reusable ssh session instead.

cm=/tmp/cm-$UID-$RANDOM$RANDOM$RANDOM
ssh -M -S "$cm" -N A &
session=$!
ssh -S "$cm" A do-thing-1
ssh          B do-thing-2
ssh -S "$cm" A do-thing-3
kill "$session"
wait "$session"

See https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing for more.

2
  • Thanks. :D Is there not a nicer way to do this without any external tools, though? There are quite a few commands that happen at different times, and putting them all in the same statement would be hard to read.
    – Ashkay
    Jul 1, 2015 at 14:55
  • For keeping multiple sessions open and communicating between them, I would be looking at Python+Paramiko or something like that instead for anything except the completely trivial case. However, see also now the updated answer with the ControlMaster hack.
    – tripleee
    Jul 2, 2015 at 6:38
1

You can use screen

$: screen
$: do-thing-1

Ctrl-A and Ctrl-D exit this screen,

$: screen
$: do-thing-2

Ctrl-A and Ctrl-D exit this screen,

$: screen
$: do-thing-2

Ctrl-A and Ctrl-D exit this screen,

view all `screen`, 
$: screen -ls

Restore screen by id,

$: screen -r <Screen ID>

Not the answer you're looking for? Browse other questions tagged or ask your own question.