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

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

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


当前回答

我认为你必须把这些答案结合起来才能得到你想要的。如果将nohup与分号结合使用,并将整个内容用引号括起来,那么您将得到:

ssh user@target "cd /some/directory; nohup myprogram > foo.out 2> foo.err < /dev/null"

这似乎对我有用。使用nohup,您不需要将&附加到要运行的命令。此外,如果您不需要读取命令的任何输出,则可以使用

ssh user@target "cd /some/directory; nohup myprogram > /dev/null 2>&1"

将所有输出重定向到/dev/null

其他回答

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

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

我认为你必须把这些答案结合起来才能得到你想要的。如果将nohup与分号结合使用,并将整个内容用引号括起来,那么您将得到:

ssh user@target "cd /some/directory; nohup myprogram > foo.out 2> foo.err < /dev/null"

这似乎对我有用。使用nohup,您不需要将&附加到要运行的命令。此外,如果您不需要读取命令的任何输出,则可以使用

ssh user@target "cd /some/directory; nohup myprogram > /dev/null 2>&1"

将所有输出重定向到/dev/null

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

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

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

实际上,每当我需要在远程机器上运行复杂的命令时,我喜欢将命令放在目标机器上的脚本中,然后使用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"