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

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

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


当前回答

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

其他回答

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

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

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

我认为你必须把这些答案结合起来才能得到你想要的。如果将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 -x remoteServer "cd yourRemoteDir; ./yourRemoteScript.sh </dev/null >/dev/null 2>&1 & " 

我试图做同样的事情,但增加了复杂性,我试图从Java来做。因此,在一台运行java的机器上,我试图在另一台机器上运行一个脚本,在后台(使用nohup)。

从命令行,这里是工作的:(如果你不需要ssh到主机,你可能不需要“-i keyFile”)

ssh -i keyFile user@host bash -c "\"nohup ./script arg1 arg2 > output.txt 2>&1 &\""

请注意,在我的命令行中,“-c”后面有一个参数,全部用引号括起来。但是为了让它在另一端工作,它仍然需要引号,所以我必须在其中添加转义引号。

从java,这是什么工作:

ProcessBuilder b = new ProcessBuilder("ssh", "-i", "keyFile", "bash", "-c",
 "\"nohup ./script arg1 arg2 > output.txt 2>&1 &\"");
Process process = b.start();
// then read from process.getInputStream() and close it.

它花了一些试验和错误来让它工作,但现在似乎工作得很好。

如果你不能/不能保持连接打开,你可以使用屏幕,如果你有权限安装它。

user@localhost $ screen -t remote-command
user@localhost $ ssh user@target # now inside of a screen session
user@remotehost $ cd /some/directory; program-to-execute &

分离屏幕会话:ctrl-a d

列出屏幕会话:

screen -ls

重新连接一个会话:

screen -d -r remote-command

注意,screen还可以在每个会话中创建多个shell。使用tmux也可以达到类似的效果。

user@localhost $ tmux
user@localhost $ ssh user@target # now inside of a tmux session
user@remotehost $ cd /some/directory; program-to-execute &

卸载tmux会话:ctrl-b d

列出屏幕会话:

tmux list-sessions

重新连接一个会话:

tmux attach <session number>

默认的tmux控制键'ctrl-b'使用起来有些困难,但有几个tmux配置的示例,您可以尝试。