Using SSH to remotely start a process

Solution 1:

SSH connects stdin, stdout and stderr of the remote shell to your local terminal, so you can interact with the command that's running on the remote side.

As a side effect, it will keep running until these connections have been closed, which happens only when the remote command and all its children (!) have terminated (because the children, which is what "&" starts, inherit std* from their parent process and keep it open).

So you need to use something like

ssh user@host "/script/to/run < /dev/null > /tmp/mylogfile 2>&1 &"

The <, > and 2>&1 redirect stdin/stdout/stderr away from your terminal. The "&" then makes your script go to the background. In production you would of course redirect stdin/err to a suitable logfile.

See

http://osdir.com/ml/network.openssh.general/2006-05/msg00017.html

Edit:

Just found out that the < /dev/null above is not necessary (but redirecting stdout/err is). No idea why...

Solution 2:

You could try nohup. Man nohup for more details.

ssh host "nohup script &"

If you want to keep the output on the remote machine, here's a variant.

ssh user@host 'export REMOTE=myname; nice nohup ./my-restart >
logfile.log 2>&1 &'

Solution 3:

Another alternative would be to fire up a detached screen(1), something like:

ssh -l user host "screen -d -m mycommand"

This will start a detached screen (which captures all the interaction inside of it) and then immediately return, terminating the ssh session.

With a bit more ingenuity, you can solve quite complex remote command calls this way.


Solution 4:

 -f      Requests ssh to go to background just before command execution.
         This is useful if ssh is going to ask for passwords or
         passphrases, but the user wants it in the background.  This
         implies -n.  The recommended way to start X11 programs at a
         remote site is with something like ssh -f host xterm.

         If the ExitOnForwardFailure configuration option is set to “yes”,
         then a client started with -f will wait for all remote port for‐
         wards to be successfully established before placing itself in the
         background.

Tags:

Ssh

Command