Execute multiple commands over ssh without reconnecting

1

I'd like to execute multiple commands through ssh from the script on my local machine, but without the need to reconnect for each command. Normally, I'd go with something like:

$ ssh [user]@[server] '[command 1] | [command 2] | [command 3]'

However this strips me of the opportunity to know the output and exit code of each command. What I'd really like to do is have ssh connection hang on somewhere in the background and then just feed it commands and receive output from it, for example (this is not valid, obviously, just an example of what I'd like it to look like):

$ ssh --name=my_connection [user]@[server]
$ ssh my_connection 'command_1'
$ ssh my_connection 'command_2'
$ ssh my_connection 'command_3'

Is it possible in any way?

snitko

Posted 2016-03-26T17:57:21.787

Reputation: 482

Answers

3

Already answered for example here on Serverfault:

You can set up ~/.ssh/config, with these options:

Host machine1
  HostName machine1.example.org
  User yourusername
  ControlPath ~/.ssh/controlmasters/%r@%h:%p
  ControlMaster auto
  ControlPersist 10m

Then make sure you mkdir ~/.ssh/controlmasters/ and from that time, your connections to machine1 will persist for 10 minutes so you can issue more sessions or data transfers during one connection.

Then it will Just WorkTM:

$ ssh [server] 'command_1'
# authenticate
$ ssh [server] 'command_2'
$ ssh [server] 'command_3'

If you have some reason not to use the config, then you can do it also on command-line:

$ ssh -MNfS ~/.ssh/controlmasters/%r@%h:%p [server]
# authenticate and go to background
$ ssh -S ~/.ssh/controlmasters/%r@%h:%p [server] 'command_1'
# authenticate
$ ssh -S ~/.ssh/controlmasters/%r@%h:%p [server] 'command_2'
$ ssh -S ~/.ssh/controlmasters/%r@%h:%p [server] 'command_3'

Jakuje

Posted 2016-03-26T17:57:21.787

Reputation: 7 981

Does "issuing a session" take additional time? Is there a way to make this work without fixing config (like, supply a command line argument to ssh? – snitko – 2016-03-26T18:30:01.090

Yes, you can use direct command-line options to ssh, but then the first one will be ssh -MNfS ~/.ssh/controlmasters/%r@%h:%p [server] and the others just ssh -S ~/.ssh/controlmasters/%r@%h:%p [server] command. But the config is much more convenient. – Jakuje – 2016-03-26T18:35:02.343