This is a follow-on question to the How do you use ssh in a shell script? question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&) at the end of the command it just hangs. The exact form of the command looks like this:
ssh user@target "cd /some/directory; program-to-execute &"
Any ideas? One thing to note is that logins to the the target machine always produce a text banner and I have SSH keys set up so no password is required.
Quickest and easiest way is to use the 'at' command:
I think this is what you need: At first you need to install
sshpass
on your machine. then you can write your own script:If you don't/can't keep the connection open you could use screen, if you have the rights to install it.
To detach the screen session: ctrl-a d
To list screen sessions:
To reattach a session:
Note that screen can also create multiple shells within each session. A similar effect can be achieved with tmux.
To detach the tmux session: ctrl-b d
To list screen sessions:
To reattach a session:
The default tmux control key, 'ctrl-b', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.
Redirect fd's
Output needs to be redirected with
&>/dev/null
which redirects both stderr and stdout to /dev/null and is a synonym of>/dev/null 2>/dev/null
or>/dev/null 2>&1
.Parantheses
The best way is to use
sh -c '( ( command ) & )'
where command is anything.Nohup Shell
You can also use nohup directly to launch the shell:
Nice Launch
Another trick is to use nice to launch the command/shell:
First follow this procedure:
Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:
Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):
Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:
From now on you can log into B as b from A as a without password:
then this will work without entering a password
ssh b@B "cd /some/directory; program-to-execute &"
I just wanted to show a working example that you can cut and paste: