Ssh – How to run ssh -t user@remote ‘sudo nohup bash -c “command”’ in background

background-processnohupsshsudo

I want to run a script on a remote host with sudo privilege,
someone suggests that I should use nohup and ssh -t, like the following command:

The script ls; sleep 10; echo finish is crafted here to resemble what I want to do.

ssh -t esolve@remote_host \
'sudo nohup bash -c "ls;sleep 100;echo finish" < /dev/null 2>&1 >> ssh.log' 

I want to run this script in background on local host
because in my script, after this command there are some other commands, like

my script.sh:

ssh -t esolve@remote_host \
'sudo nohup bash -c "ls;sleep 100;echo finish" < /dev/null 2>&1 >> ssh.log' 
... some other commands

the following two commands don't work

ssh -t esolve@remote_host \
'sudo nohup bash -c "ls;sleep 100;echo finish" < /dev/null 2>&1 >> ssh.log' &

ssh -t esolve@remote_host \
'sudo nohup bash -c "ls;sleep 100;echo finish" < /dev/null 2>&1 >> ssh.log &' 

Why?

And how can I make this command run in background of local host?
Besides, I don't need to input password for sudo on remote host.

Best Answer

Add the -b flag to sudo, which prompts for password if needed and then goes to the background. (The redirect also needs to be done within bash) (Curly brackets are needed to get the redirection to apply to everything)

ssh -t esolve@remote_host 'sudo -b nohup bash -c "{ ls;sleep 100;echo finish; } < /dev/null 2>&1 >> ssh.log"'

You might also want to try screen instead...

ssh -t esolve@remote_host 'sudo -b screen -m -d bash -c "{ ls;sleep 100;echo finish; } < /dev/null 2>&1 >> ssh.log"'
Related Question