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

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

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


当前回答

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

其他回答

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

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配置的示例,您可以尝试。

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

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

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

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

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

对我来说,使用tmux new -d <shell cmd>语法进行远程tmux会话似乎非常方便:

ssh someone@elsewhere 'tmux new -d sleep 600'

这将在其他主机上启动新会话,本地机器上的ssh命令将几乎立即返回shell。然后您可以通过ssh连接到远程主机,并将tmux附加到该会话。注意,没有本地tmux运行,只有远程运行!

另外,如果你想让你的会话在任务完成后继续,只需在命令后添加一个shell启动器,但不要忘记用引号括起来:

ssh someone@elsewhere 'tmux new -d "~/myscript.sh; bash"'

这对我来说很有效:

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