你如何后台 ssh 进程?

dan*_*dan 9 ssh job-control

我知道您可以使用 ~^z 暂停 ssh 会话,但是是否还有一种方法可以将其设为后台,以便在您在本地 shell 中执行其他操作时继续工作?

小智 12

如果您尝试远程运行进程,并且不关心 ssh 会话保持打开状态,则可能需要考虑使用screen. 它将允许您在“后台”运行您的进程,并在您注销后继续运行。

首先,ssh转到远程框,然后从那里使用screen并启动您的过程,screen如果需要,您可以提供会话名称。您不会真正注意到任何不同,但在该会话中开始您的过程。您可以screen使用命令退出会话Ctrl-a d。它看起来像这样:

user@remotebox:~$ screen -S foobarsession
user@remotebox:~$ startmyprocess
[detached from 4865.foobarsession]
user@remotebox:~$
Run Code Online (Sandbox Code Playgroud)

然后您可以退出 ssh 会话,该进程将继续运行。要screen稍后重新连接到会话,请 ssh 回到远程框并使用screen -r重新连接。您可以使用screen -ls来列出会话。

user@remotebox:~$ screen -ls
There is a screen on:
        4865.foobarsession     (10/05/2012 11:10:57 AM)     (Detached)
1 Socket in /var/run/screen/S-user
user@remotebox:~$ screen -r foobarsession
user@remotebox:~$ screen -ls
        4865.foobarsession     (10/05/2012 11:10:57 AM)     (Attached)
1 Socket in /var/run/screen/S-user
user@remotebox:~$
Run Code Online (Sandbox Code Playgroud)

或者,如果screen未安装,您可以使用nohup远程盒子上的命令。维基百科很好地解释了这一点:

Nohupping backgrounded jobs is typically used to avoid terminating them when logging
off from a remote SSH session. A different issue that often arises in this situation
is that ssh is refusing to log off ("hangs"), since it refuses to lose any data
from/to the background job(s).  This problem can also be overcome by redirecting all
three I/O streams:

nohup ./myprogram > foo.out 2> foo.err < /dev/null &
Run Code Online (Sandbox Code Playgroud)

所以你可以这样做:

ssh -n -f user@remotebox "sh -c 'cd /foo/bar; nohup ./myprogram > foo.out 2> foo.err < /dev/null &'"
Run Code Online (Sandbox Code Playgroud)


yan*_*kee 9

~^z 执行后bg,停止的进程将继续在后台执行。适用于所有进程,而不仅仅是 ssh。

PS:随着fg您再次将后台进程置于前台。只是为了记录: ~ 只需要区分挂起是在本地机器上(有 ~ --> ssh 客户端)还是在服务器上(没有 ~ --> 当前在前台运行的任何进程服务器)