Close, but not exactly.
Independently of any terminal
ssh root@remoteserver '/root/backup.sh </dev/null >/var/log/root-backup.log 2>&1 &'
You need to close all file descriptors that are connected to the ssh socket, because the ssh session won't close as long as some remote process has the socket open. If you aren't interested in the script's output (presumably because the script itself takes care of writing to a log file), redirect it to /dev/null
(but note that this will hide errors such as not being able to start the script).
Using nohup
has no useful effect here. nohup
arranges for the program it runs not to receive a HUP signal if the program's controlling terminal disappears, but here there is no terminal in the first place, so nothing is going to send a SIGHUP to the process out of the blue. Also, nohup
redirects standard output and standard error (but not standard input) to a file, but only if they're connected to a terminal, which, again, they aren't.
Detaching from a terminal
aaron@localpc$ ssh root@remoteserver
root@remoteserver# nohup /root/backup.sh </dev/null &
nohup: appending output to `nohup.out'
[1] 12345
root@remoteserver# exit
aaron@localpc$
Use nohup
to detach the script from its controlling terminal so that it doesn't receive a SIGHUP when the terminal disappears. nohup
also redirects the script's standard output and standard error to a file called nohup.out
if they're connected to the terminal; you have to take care of standard input yourself.
Keeping a remote terminal
If you want to keep the command running in a remote terminal but not have it attached to the SSH session, run it in a terminal multiplexer such as Screen or Tmux.
ssh root@remoteserver 'screen -S backup -d -m /root/backup.sh'
You can later reconnect to the terminal where the script is running by invoking screen -S backup -rd
as root on that machine.
Automating one remote command
For slightly better security, don't open direct remote root logins too widely. Create a special-purpose key pair and give it a forced command in /root/.ssh/authorized_keys
. The contents of the public key file is AAAA…== wibble@example.com
; add a comma-separated list of options including command="…"
which specifies that the key can only be used to execute this specific command. Be sure to keep the options and the key all on one line.
command="/root/backup.sh </dev/null >/dev/null 2>/dev/null &",no-port-forwarding,no-agent-forwarding,no-x11-forwarding,no-pty,no-user-rc AAAA…== wibble@example.com