这是一个后续的问题,你如何使用ssh在一个shell脚本?的问题。如果我想在远程机器上执行在后台运行的命令,如何返回ssh命令?当我试图在命令末尾只包含&号时,它就挂起了。命令的确切形式如下所示:

ssh user@target "cd /some/directory; program-to-execute &"

什么好主意吗?需要注意的一件事是,登录到目标机器总是产生一个文本横幅,我设置了SSH密钥,所以不需要密码。


当前回答

你可以这样做……

sudo /home/script.sh -opt1 > /tmp/script.out &

其他回答

没有nohup你也可以做到:

ssh user@host 'myprogram >out.log 2>err.log &'

这对我来说是最干净的方式:-

ssh -n -f user@host "sh -c 'cd /whereever; nohup ./whatever > /dev/null 2>&1 &'"

在此之后唯一运行的是远程计算机上的实际命令

我只是想展示一个你可以剪切和粘贴的工作示例:

ssh REMOTE "sh -c \"(nohup sleep 30; touch nohup-exit) > /dev/null &\""

如果使用zsh,则使用程序执行&!是zsh特定于后台和否认进程的快捷方式,这样退出shell将使其继续运行。

实际上,每当我需要在远程机器上运行复杂的命令时,我喜欢将命令放在目标机器上的脚本中,然后使用ssh运行该脚本。

例如:

# simple_script.sh (located on remote server)

#!/bin/bash

cat /var/log/messages | grep <some value> | awk -F " " '{print $8}'

然后我在源机器上运行这个命令:

ssh user@ip "/path/to/simple_script.sh"