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

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

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


当前回答

@cmcginty简洁的工作示例的后续内容,该示例还展示了如何用双引号替换外部命令。这是在PowerShell脚本中调用模板的样子(该脚本只能从双引号中插入变量,而忽略单引号中包装的任何变量展开):

ssh user@server "sh -c `"($cmd) &>/dev/null </dev/null &`""

内双引号用反标记而不是反斜杠进行转义。这允许$cmd由PowerShell脚本组成,例如用于部署脚本和自动化等。如果使用unix LF组合,$cmd甚至可以包含多行heredoc。

其他回答

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

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

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

这对我来说很有效:

ssh -x remoteServer "cd yourRemoteDir; ./yourRemoteScript.sh </dev/null >/dev/null 2>&1 & " 
YOUR-COMMAND &> YOUR-LOG.log &    

这应该运行该命令并分配一个进程id,您可以简单地跟踪-f YOUR-LOG.log以查看发生时写入该进程的结果。您可以在任何时候注销,这个过程将继续进行

If you run remote command without allocating tty, redirect stdout/stderr works, nohup is not necessary. ssh user@host 'background command &>/dev/null &' If you use -t to allocate tty to run interactive command along with background command, and background command is the last command, like this: ssh -t user@host 'bash -c "interactive command; nohup backgroud command &>/dev/null &"' It's possible that background command doesn't actually start. There's race here: bash exits after nohup starts. As a session leader, bash exit results in HUP signal sent to nohup process. nohup ignores HUP signal. If 1 completes before 2, the nohup process will exit and won't start the background command at all. We need to wait nohup start the background command. A simple workaroung is to just add a sleep: ssh -t user@host 'bash -c "interactive command; nohup backgroud command &>/dev/null & sleep 1"'

这个问题在几年前就被提出和回答了,我不知道openssh的行为从那时起是否发生了变化。我在测试: OpenSSH_8.6p1, OpenSSL 1.1.1g FIPS 21 Apr 2020

最快和最简单的方法是使用'at'命令:

ssh user@target "at now -f /home/foo.sh"