让 ssh 在目标机器的后台执行命令 [英] Getting ssh to execute a command in the background on target machine

查看:57
本文介绍了让 ssh 在目标机器的后台执行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是How do您在 shell 脚本中使用 ssh 吗? 问题.如果我想在该机器后台运行的远程机器上执行命令,我如何让 ssh 命令返回?当我尝试在命令末尾包含与号 (&) 时,它只是挂起.命令的确切形式如下所示:

This is a follow-on question to the How do you use ssh in a shell script? question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&) at the end of the command it just hangs. The exact form of the command looks like this:

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

有什么想法吗?需要注意的一件事是,登录目标机器总是会产生一个文本横幅,而且我设置了 SSH 密钥,因此不需要密码.

Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have SSH keys set up so no password is required.

推荐答案

我在一年前编写的一个程序中遇到了这个问题——结果证明答案相当复杂.您需要使用 nohup 以及输出重定向,如 nohup 上的维基百科文章中所述,为方便起见复制到这里.

I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on nohup, copied here for your convenience.

Nohuping 后台作业适用于通过 SSH 登录时有用的示例,因为后台作业会导致由于比赛而导致退出的外壳挂起条件 [2].这个问题也可以通过重定向所有三个来克服I/O 流:

Nohuping backgrounded jobs is for example useful when logged in via SSH, since backgrounded jobs can cause the shell to hang on logout due to a race condition [2]. This problem can also be overcome by redirecting all three I/O streams:

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

这篇关于让 ssh 在目标机器的后台执行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆