How to launch a remote process through ssh and end the connection?

3

3

This is still blocking:

ssh host nohup cmd

This still leaves the connection open:

ssh host nohup cmd &

Łukasz Lew

Posted 2010-03-22T19:15:58.987

Reputation:

Is there really no way to properly do this? I've been struggling all day, and none of the options seem to leave the remote process running AND terminate the local SSH process. The best I've got so far is to run the SSH in the background, wait 15 seconds, then kill the PID. But that's ugly. – Hammer Bro. – 2011-05-23T22:25:28.437

Answers

1

Try this:

ssh host batch cmd

Mox

Posted 2010-03-22T19:15:58.987

Reputation: 589

This is a nice approach, but note that batch depends on having a working cron/at system on the remote system. – coneslayer – 2010-03-26T17:46:47.507

1

The & in your example will detach the ssh command, but not your remote program.

This seems to work:

ssh remote-host 'tail -f /var/log/syslog &' &

ssh remote-host 'tail -f /var/log/syslog > /dev/null &' &

The first & will detach the command for the remote host, and the second & will detach the ssh command itself

In my example, the tail command is still running after I've closed the connection.


edit this does not seems to work as tail exits shortly after the connection is actually closed.

This may be related to the fact that it's writing to STDOUT which will probably raise a broken pipe after the connection is closed

edit 2 works fine when redirecting the tail command to /dev/null ^_^

Just be careful and don't write to stderr / stdout, or redirect the output to a local destination

Romuald Brunet

Posted 2010-03-22T19:15:58.987

Reputation: 113

0

The following will work:

ssh myhost " nohup ./r.sh & " & sleep 2 ; kill -9 $! && echo

(at least if you are not prompted for a password). In case you are I don't see a easy way to do it.

skeept

Posted 2010-03-22T19:15:58.987

Reputation: 255

0

This issue is apparently long standing (even longer than your question!). The solution is to redirect stdout and stderr. The text book example is this:

ssh server 'sleep 20 & exit'

which hangs for 20 seconds. Using bash you can rewrite it to:

ssh server 'sleep 20 >/dev/null 2>&1 & exit'

which fixes the issue. For tcsh you would use something along the lines of:

ssh server '(sleep 20 >/dev/null) >& /dev/null & exit'

References

Paul

Posted 2010-03-22T19:15:58.987

Reputation: 101