2

I want to run some script through ssh and detach it, so it run even after ssh session is closed. I need to do this with sudo.

I can run some script but I am not able to detach it. I tried following commands:

ssh 10.0.139.120 -t "sudo -b nohup some_script"

and

ssh 10.0.139.120 -t "sudo nohup some_script &"

Neither of above worked. Every time I get communicate "Connection to 10.0.139.171 closed." and no process is running on server.

I have also tried to do it with screen:

ssh 10.0.139.120 -t "sudo screen -S script -md some_script"

It did not work either, even though command works when I enter it on server locally. How can I do it then?

sbagin13
  • 153
  • Do you mean the script needs to be run with sudo? I’d try: ssh 10.0.139.120 -t 'sudo sh -c "nohup some_script &"' – dessert Jan 18 '19 at 12:40
  • I have managed to do it with tmux, but I really would like to know why can'I I do it other way. – sbagin13 Jan 18 '19 at 13:07
  • https://unix.stackexchange.com/questions/30400/execute-remote-commands-completely-detaching-from-the-ssh-connection – Simon Sudler Jan 18 '19 at 13:28
  • Thanks, I saw that already, but I don't know why this solution doesn't work for me. – sbagin13 Jan 18 '19 at 13:38
  • 1
    It would really help if you could [edit] your question and explain how each of these "didn't work". Did the command not run at all? Did it run but was stopped when you disconnected? Something else? Telling us how they failed will let us understand why they failed and possibly answer you. – terdon Jan 18 '19 at 15:21

2 Answers2

3

I did small survey and found this similar question on Stack Overflow. At all you must add path to the script or must go inside the directory, where the script is located:

ssh remote-host -t "sudo -b sh -c 'nohup /path/some_script > /dev/null 2>&1 &'"
ssh remote-host -t "sudo -b sh -c 'cd /path; nohup ./some_script > /dev/null 2>&1 &'"

Without sh -c or bash -c the ampersand & at the end breaks the command in some way.


I couldn't manage to use disown for this purpose, but setsid works well:

 ssh remote-host -t 'sudo -b setsid /path/some_script'
pa4080
  • 29,831
  • Any idea why I can't start and detach script on guest system (Ubuntu server) in VirtualBox? In the other direction it works. I can start session on host from guest. – sbagin13 Feb 12 '19 at 13:55
  • Hi, @sbagin13, I do not have any experience with VirtualBox. Is it possible to be an issue with the $PATH envvar? Try to redirect the output to some file instead of /dev/null, maybe this log will provide some useful information. – pa4080 Feb 12 '19 at 14:47
0

You can try using disown to avoid the process being killed after you close you ssh session.