how to run a command in background using ssh and detach the session

Progress Programmer picture Progress Programmer · Oct 27, 2009 · Viewed 41.5k times · Source

I'm currently trying to ssh into a remote machine and run a script, then leave the node with the script running. Below is my script. However, when it runs, the script is successfully run on the machine but ssh session hangs. What's the problem?

ssh -x $username@$node 'rm -rf statuslist
                        mkdir statuslist
                        chmod u+x ~/monitor/concat.sh
                        chmod u+x ~/monitor/script.sh
                        nohup ./monitor/concat.sh &
                        exit;'

Answer

Jayan picture Jayan · Feb 17, 2010

There are some situations when you want to execute/start some scripts on a remote machine/server (which will terminate automatically) and disconnect from the server.

eg: A script running on a box which when executed

  1. takes a model and copies it to a remote server
  2. creates a script for running a simulation with the model and push it to server
  3. starts the script on the server and disconnect
  4. The duty of the script thus started is to run the simulation in the server and once completed (will take days to complete) copy the results back to client.

I would use the following command:

ssh remoteserver 'nohup /path/to/script `</dev/null` >nohup.out 2>&1 &'

@CKeven, you may put all those commands on one script, push it to the remote server and initiate it as follows:

echo '#!/bin/bash  
rm -rf statuslist  
mkdir statuslist  
chmod u+x ~/monitor/concat.sh  
chmod u+x ~/monitor/script.sh  
nohup ./monitor/concat.sh &  
' > script.sh

chmod u+x script.sh

rsync -azvp script.sh remotehost:/tmp

ssh remotehost '/tmp/script.sh `</dev/null` >nohup.out 2>&1 &'

Hope this works ;-)

Edit: You can also use ssh user@host 'screen -S SessionName -d -m "/path/to/executable"'

Which creates a detached screen session and runs target command within it