代码之家  ›  专栏  ›  技术社区  ›  dagorym

让ssh在目标机器的后台执行命令

  •  362
  • dagorym  · 技术社区  · 17 年前

    这是一个后续问题 How do you use ssh in a shell script? 问题。如果我想在远程机器上执行一个在该机器后台运行的命令,我如何让ssh命令返回?当我试图在命令末尾只包含与号(&)时,它就会挂起。命令的确切形式如下:

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

    有什么想法吗?需要注意的一点是,登录到目标机器总是会产生一个文本横幅,我有 SSH 密钥设置为不需要密码。

    19 回复  |  直到 5 年前
        1
  •  2
  •   Fang Zhen    2 年前

    这应该能解决你的问题:

    nohup myprogram > foo.log 2> foo.err < /dev/null &
    

    语法和不寻常的用法 < /dev/null 解释得特别好 in this answer ,为方便起见,在此引用。

    </dev/null 用于立即向程序发送EOF,以便 不等待输入( /dev/null 空设备是一个特殊的文件 它会丢弃写入其中的所有数据,但会报告写入 操作成功,并且没有向任何读取的进程提供数据 从中立即产生EOF)。

    所以命令:

    nohup myscript.sh >myscript.log 2>&1 </dev/null &
    #\__/             \___________/ \__/ \________/ ^
    # |                    |          |      |      |
    # |                    |          |      |  run in background
    # |                    |          |      |
    # |                    |          |   don't expect input
    # |                    |          |   
    # |                    |        redirect stderr to stdout
    # |                    |           
    # |                    redirect stdout to myscript.log
    # |
    # keep the command running 
    # no matter whether the connection is lost or you logout
    

    将把命令移到后台,输出stdout和 stderr到myscript.log,无需等待任何输入。


    另请参阅维基百科上的文章 nohup ,为方便起见,也在此引用。

    Nohuping背景工作是为了 示例在通过SSH登录时很有用, 因为背景作业可能会导致 shell因比赛而暂停注销 条件。这个问题也可能 通过重定向所有三个来克服 I/O流。

        2
  •  0
  •   mdisibio    2 年前

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

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

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