10

I'm sshing into a server and I'm starting a Python script that'll take approx. 24 hours to complete. What if my internet connection dies in the middle? Will that stop the command?

Is there any way to run my long-running command in a way that local disconnects won't affect it and I could continue to see its output after I log in to ssh again?

29

The best way is to use screen (on the server) to start a session to run the command in and then disconnect the screen so it will keep running, and you can do other things, or just disconnect from the server. The other option is to use nohup in combination with & so you would have nohup <command> &

  • Screen. Or you can setup a cron task if its something you run more then once. – xeon Aug 19 '10 at 19:54
  • 2
    If you get disconnected while it's running in screen, screen -r will reconnect you. – dpflug Aug 19 '10 at 21:41
2

You can also use disown if you've already started the process without screen or nohup

1

If you background a process & close your session the process will get adopted by init (PID 1).

If I have a session and do:

]$ sleep 10000 &
]$ exit

and open another session and run:

]$ ps -ef | grep sleep
501      26387     1  0 16:37 ?        00:00:00 sleep 10000
root     26422 21360  0 16:40 pts/0    00:00:00 grep sleep

My process is still running, and we see that its parent process is now 1 (init).

Alternatively you could set up your script like you would a daemon. A quick search turns up this seemingly useful link: http://onlamp.com/python/pythoncook2/solution.csp?day=1. If you wanted to take that approach.

1

The existing answers can work well, but I needed something for BusyBox (a shell and set of tools for minimal hardware like home routers). My system does not have screen, dtach, at, disown, or even nohup! So thanks to tbc0 on SO (link), I found this gem. It returns immediately but the server process continues to run:

ssh myserver 'sleep 100 >&- 2>&- <&- &'

Or, if multiple commands are needed:

ssh myserver '(echo one; sleep 100; echo two; sleep 200) >&- 2>&- <&- &'

Explanation:

  • >&- - close stdout handle
  • 2>&- - close stderr
  • <&- - close stdin
  • & - put process in background

This uses no external programs and should work across ksh, ash, Bourne shell, bash, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.