让 ssh 在目标机器上后台执行命令
这是如何使用 ssh 的后续问题在 shell 脚本中? 问题。 如果我想在远程机器上执行在该机器后台运行的命令,如何让 ssh 命令返回? 当我尝试在命令末尾包含与号 (&) 时,它会挂起。 该命令的确切形式如下所示:
ssh user@target "cd /some/directory; program-to-execute &"
有什么想法吗? 需要注意的一件事是,登录到目标计算机总是会生成一个文本横幅,并且我设置了 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 &"
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
这应该可以解决您的问题:
< 的语法和异常使用 /dev/null
在这个答案中解释得特别好,为了方便起见,在这里引用。另请参阅 nohup 上的维基百科文章,为方便起见,也在此引用。
This should solve your problem:
The syntax and unusual use of
< /dev/null
are explained especially well in this answer, quoted here for your convenience.See also the wikipedia artcle on nohup, also quoted here for your convenience.
如果您不/无法保持连接打开,您可以使用 screen,如果您有权安装它。
分离 screen 会话: ctrl-a d
列出 screen 会话:
重新附加会话:
请注意,screen 还可以在每个会话中创建多个 shell。 使用 tmux 也可以实现类似的效果。
分离 tmux 会话:ctrl-b d
列出屏幕会话:
重新附加会话:
默认 tmux 控制键“ctrl-b',有点难以使用,但是 tmux 附带了几个示例 tmux 配置,您可以尝试。
If you don't/can't keep the connection open you could use screen, if you have the rights to install it.
To detach the screen session: ctrl-a d
To list screen sessions:
To reattach a session:
Note that screen can also create multiple shells within each session. A similar effect can be achieved with tmux.
To detach the tmux session: ctrl-b d
To list screen sessions:
To reattach a session:
The default tmux control key, 'ctrl-b', is somewhat difficult to use but there are several example tmux configs that ship with tmux that you can try.
重定向 fd 的
输出需要使用
>/dev/null
进行重定向,它将 stderr 和 stdout 重定向到 /dev/null,并且是>/dev/null 2> 的同义词。 /dev/null
或>/dev/null 2>&1
。括号
最好的方法是使用
sh -c '( ( command ) & )'
其中 command 可以是任何内容。Nohup Shell
您还可以直接使用 nohup 来启动 shell:
Nice Launch
另一个技巧是使用 Nice 来启动命令/shell:
Redirect fd's
Output needs to be redirected with
&>/dev/null
which redirects both stderr and stdout to /dev/null and is a synonym of>/dev/null 2>/dev/null
or>/dev/null 2>&1
.Parantheses
The best way is to use
sh -c '( ( command ) & )'
where command is anything.Nohup Shell
You can also use nohup directly to launch the shell:
Nice Launch
Another trick is to use nice to launch the command/shell:
这对我来说是最干净的方法:-
在此之后运行的唯一事情是远程计算机上的实际命令
This has been the cleanest way to do it for me:-
The only thing running after this is the actual command on the remote machine
我认为这就是你所需要的:
首先,您需要在计算机上安装
sshpass
。然后你可以编写自己的脚本:
I think this is what you need:
At first you need to install
sshpass
on your machine.then you can write your own script:
首先按照以下步骤操作:
以用户a登录A,生成一对认证密钥。 不输入密码:
现在使用 ssh 在 B 上以用户 b 的身份创建目录 ~/.ssh。(该目录可能已经存在,这很好):
最后将 a 的新公钥附加到 b@B:.ssh/authorized_keys最后一次输入 b 的密码:
从现在开始,您可以从 A 以 b 的身份登录 B,而无需输入密码:
这样就无需输入密码
ssh b@B "cd /some/directory; program-to-execute & ;”
First follow this procedure:
Log in on A as user a and generate a pair of authentication keys. Do not enter a passphrase:
Now use ssh to create a directory ~/.ssh as user b on B. (The directory may already exist, which is fine):
Finally append a's new public key to b@B:.ssh/authorized_keys and enter b's password one last time:
From now on you can log into B as b from A as a without password:
then this will work without entering a password
ssh b@B "cd /some/directory; program-to-execute &"
@cmcginty 的简洁工作示例的后续示例,该示例还展示了如何将外部命令用双引号括起来。 这是从
PowerShell
脚本中调用时模板的外观(该脚本只能从双引号内插入变量,并在用单引号括起来时忽略任何变量扩展):内部双引号被转义用反勾号代替反斜杠。 这允许
$cmd
由PowerShell
脚本组成,例如用于部署脚本和自动化等。 如果与 unixLF
组合,$cmd
甚至可以包含多行heredoc
。A follow-on to @cmcginty's concise working example which also shows how to alternatively wrap the outer command in double quotes. This is how the template would look if invoked from within a
PowerShell
script (which can only interpolate variables from within double-quotes and ignores any variable expansion when wrapped in single quotes):Inner double-quotes are escaped with back-tick instead of backslash. This allows
$cmd
to be composed by thePowerShell
script, e.g. for deployment scripts and automation and the like.$cmd
can even contain a multi-lineheredoc
if composed with unixLF
.这应该运行命令并分配一个进程 ID,您可以简单地 tail -f YOUR-LOG.log 来查看写入的结果。 您可以随时注销,该过程将继续
This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on
如果您使用的是 zsh,则使用
program-to-execute &!
是 zsh 特定的快捷方式,可通往后台并拒绝进程,这样退出 shell 就会使其继续运行。If you are using zsh then use
program-to-execute &!
is a zsh-specific shortcut to both background and disown the process, such that exiting the shell will leave it running.实际上,每当我需要在远程计算机上运行一个复杂的命令时,我喜欢将该命令放入目标计算机上的脚本中,然后使用 ssh 运行该脚本。
例如:
然后我只需在源计算机上运行此命令:
Actually, whenever I need to run a command on a remote machine that's complicated, I like to put the command in a script on the destination machine, and just run that script using ssh.
For example:
And then I just run this command on the source machine:
我试图做同样的事情,但由于我试图通过 Java 来完成它,所以增加了复杂性。 因此,在一台运行java的机器上,我试图在另一台机器上在后台运行脚本(使用nohup)。
从命令行,这是有效的:(如果不需要“-i keyFile”来 ssh 到主机,则可能不需要它)
请注意,对于我的命令行,“-c”后面有一个参数",全部用引号引起来。 但为了让它在另一端工作,它仍然需要引号,所以我必须在其中添加转义引号。
从java中,这是有效的:
它需要一些尝试& 让它工作时出错,但现在似乎工作得很好。
I was trying to do the same thing, but with the added complexity that I was trying to do it from Java. So on one machine running java, I was trying to run a script on another machine, in the background (with nohup).
From the command line, here is what worked: (you may not need the "-i keyFile" if you don't need it to ssh to the host)
Note that to my command line, there is one argument after the "-c", which is all in quotes. But for it to work on the other end, it still needs the quotes, so I had to put escaped quotes within it.
From java, here is what worked:
It took a bit of trial & error to get this working, but it seems to work well now.
如果您在未分配 tty 的情况下运行远程命令,则重定向
stdout/stderr
有效,nohup
不是必需的。ssh user@host '后台命令 &>/dev/null &'
如果使用
-t
分配tty与后台一起运行交互式命令命令,后台命令是最后一个命令,如下所示:ssh -t user@host 'bash -c "交互式命令; nohup 后台命令 &>/dev/null &"'
后台命令
可能实际上并未启动。 这里有比赛:bash
在nohup
启动后退出。 作为会话领导者,bash
退出会导致HUP
信号发送至nohup
进程。nohup
忽略HUP
信号。如果
1
在2
之前完成,nohup
进程将退出并且不会启动后台命令
根本不。 我们需要等待nohup
启动后台命令
。 一个简单的解决方法是添加一个sleep
:ssh -t user@host 'bash -c "交互式命令; nohup 后台命令 &>/dev/null & sleep 1"'
这个问题是几年前提出并回答的,我不知道从那时起 openssh 的行为是否发生了变化。 我正在测试:
OpenSSH_8.6p1,OpenSSL 1.1.1g FIPS 2020 年 4 月 21 日
If you run remote command without allocating tty, redirect
stdout/stderr
works,nohup
is not necessary.ssh user@host 'background command &>/dev/null &'
If you use
-t
to allocate tty to run interactive command along with background command, and background command is the last command, like this:ssh -t user@host 'bash -c "interactive command; nohup backgroud command &>/dev/null &"'
It's possible that
background command
doesn't actually start. There's race here:bash
exits afternohup
starts. As a session leader,bash
exit results inHUP
signal sent tonohup
process.nohup
ignoresHUP
signal.If
1
completes before2
, thenohup
process will exit and won't start thebackground command
at all. We need to waitnohup
start thebackground command
. A simple workaroung is to just add asleep
:ssh -t user@host 'bash -c "interactive command; nohup backgroud command &>/dev/null & sleep 1"'
The question was asked and answered years ago, I don't know if openssh behavior changed since then. I was testing on:
OpenSSH_8.6p1, OpenSSL 1.1.1g FIPS 21 Apr 2020
使用
tmux new -d
语法进行远程 tmux 会话对我来说似乎非常方便,如下所示:这将在
上启动新会话其他地方
本地计算机上的主机和 ssh 命令几乎会立即返回 shell。 然后,您可以 ssh 到远程主机并将 tmux Attach 到该会话。 请注意,本地 tmux 运行没有任何内容,只有远程运行!另外,如果您希望会话在工作完成后持续存在,只需在命令后添加 shell 启动器,但不要忘记用引号引起来:
It appeared quite convenient for me to have a remote tmux session using the
tmux new -d <shell cmd>
syntax like this:This will launch new session on
elsewhere
host and ssh command on local machine will return to shell almost instantly. You can then ssh to the remote host andtmux attach
to that session. Note that there's nothing about local tmux running, only remote!Also, if you want your session to persist after the job is done, simply add a shell launcher after your command, but don't forget to enclose in quotes:
你可以这样做...
You can do it like this...
这对我来说可能多次有效:
This worked for me may times:
最快、最简单的方法是使用“at”命令:
Quickest and easiest way is to use the 'at' command:
我认为你必须结合这些答案才能得到你想要的。 如果您将 nohup 与分号结合使用,并将整个内容用引号引起来,那么您会得到:
这似乎对我有用。 使用 nohup,您不需要附加 & 到要运行的命令。 另外,如果您不需要读取命令的任何输出,则可以使用
将所有输出重定向到 /dev/null。
I think you'll have to combine a couple of these answers to get what you want. If you use nohup in conjunction with the semicolon, and wrap the whole thing in quotes, then you get:
which seems to work for me. With nohup, you don't need to append the & to the command to be run. Also, if you don't need to read any of the output of the command, you can use
to redirect all output to /dev/null.
我只是想展示一个可以剪切和粘贴的工作示例:
I just wanted to show a working example that you can cut and paste:
您可以在不使用 nohup 的情况下执行此操作:
You can do this without nohup: