终止由bash脚本执行的SSH会话

mah*_*off 18 ssh bash

我有一个脚本,我可以在本地运行远程启动服务器:

#!/bin/bash
ssh user@host.com <<EOF
  nohup /path/to/run.sh &
EOF
echo 'done'
Run Code Online (Sandbox Code Playgroud)

运行nohup后,它会挂起.我必须按ctrl-c退出脚本.

我已经尝试在here doc的末尾添加一个显式退出,并为ssh使用"-t"参数.两者都不起作用.如何立即退出此脚本?

编辑:客户端是OSX 10.6,服务器是Ubuntu.

mar*_*ton 16

我认为问题是当你从ssh进来时nohup无法重定向输出,只有当它认为它连接到终端时它才会重定向到nohup.out,并且我的stdin覆盖你将阻止它,即使有-t.

解决方法可能是自己重定向输出,然后ssh客户端可以断开连接 - 它不等待流关闭.就像是:

nohup /path/to/run.sh > run.log &
Run Code Online (Sandbox Code Playgroud)

(这对我来说是一个简单的测试,从OS X客户端连接到Ubuntu服务器.)


小智 8

问题可能是......

... ssh is respecting the POSIX standard when not closing the session 
if a process is still attached to the tty.
Run Code Online (Sandbox Code Playgroud)

因此,一个解决办法可能是卸下stdin了的nohup从tty命令:

nohup /path/to/run.sh </dev/null &
Run Code Online (Sandbox Code Playgroud)

请参阅:使用nohup时,SSH在退出时挂起

另一种方法可能是使用ssh -t -t强制伪tty分配,即使stdin它不是终端.

man ssh | less -Ip 'multiple -t'

ssh -t -t user@host.com <<EOF
  nohup /path/to/run.sh &
EOF
Run Code Online (Sandbox Code Playgroud)

请参阅:BASH为SSH创建子shell并继续执行程序流程