0

I am trying to create a single script that starts an ssh session, and execute commands on the remote machine, then backgrounds the session. So far I've been playing with the -f or -f -N options, but I don't know how to bring the session back to the foreground to verify my commands executed correctly.

Or is there a way that a single script can start the ssh session and continue inputting commands to that newly opened session? and then background that session? If none of those work I was thinking another way of doing this is a script that starts an ssh session, upload and execute the commands via another script.

any ideas on how to do this.

John Saunders
  • 160,644
  • 26
  • 247
  • 397

1 Answers1

1

It is not clear what you are trying to do. I'll try to be helpful.

A series of commands can be issued sequentially in a single ssh session using a single quoted string with commands separated by semicolons.

$ ssh user@remotehost 'ls; echo  foo > bar; cat bar; rm bar'

It will return the result of the last command run.

I'm confused about why you want to background the session.

If you need You can start a long running process on the remote machine with nohup and then close the session.

If you just need a series of commands run that each depend on the result of the last one, you don't need to background the process, just put that logic into your command sequence.

$ ssh user@remotehost 'if ![ -f bar ];then echo  foo > bar && cat bar && rm bar; fi'

No harm in multiple sequential ssh and scp connections if there are a lot of things to be done.

Joshua Clayton
  • 1,669
  • 18
  • 29
  • My idea behind backgrounding the ssh session is so that after the remote commands are executed the session will stay open and the script can go back to executing commands locally. – user3219834 Apr 07 '14 at 04:14
  • I'd suggest you get it working sequentially first, then try backgrounding. But my experience is adding parallelism is often more trouble than it is worth. You will need a different method to verify the results if you background, such as http://stackoverflow.com/questions/356100/how-to-wait-in-bash-for-several-subprocesses-to-finish-and-return-exit-code-0 – Joshua Clayton Apr 07 '14 at 04:22