如何在后台正确打开 SSH 隧道?

bad*_*adp 12 ssh

我希望通过 SSH 从远程主机建立端口隧道。我希望将其实现为oclif插件;我希望用户体验是这样的:

\n
laptop$ give-jupyter\nhttp://localhost:4040/\nlaptop$ kill-jupyter\nlaptop$\n
Run Code Online (Sandbox Code Playgroud)\n

...这应该相对简单;我只是*需要维护一个pidfile,对吧?就像是:

\n
laptop$ give-jupyter\nhttp://localhost:4040/\nlaptop$ kill-jupyter\nlaptop$\n
Run Code Online (Sandbox Code Playgroud)\n

然而,这一切基本上都不是重点。问题是我必须弄清楚这些标志!哦,那好吧; 这有效:

\n
import child_process from \'child_process\';\nconst childProcess = child_process.spawn(\'ssh\', [/* flags */], {detached: true, stdio: \'ignore\'});\nchildProcess.unref();\nwriteToSomePidfile({childProcess.pid);\n
Run Code Online (Sandbox Code Playgroud)\n

...但是,它还会在远程端打开一个 shell。没问题,man ssh这就是用途-L:

\n
laptop$ ssh machine -L 4040:localhost:4040\nmachine$ \n
Run Code Online (Sandbox Code Playgroud)\n

这很好,但它现在正在劫持我用户的 shell。好吧,让我们将进程发送到后台:

\n
laptop$ ssh machine -LN 4040:localhost:4040\n\n
Run Code Online (Sandbox Code Playgroud)\n

后台版本ssh进入竞争状态,外壳结束STDIN,一切都非常糟糕。好吧,man ssh说的就是这个-n:

\n
laptop$ ssh machine -LN 4040:localhost:4040 &\nlaptop$ f\nf: file not found\nlaptop$ fg\n^C\n
Run Code Online (Sandbox Code Playgroud)\n

...嗯,那太好了:ssh现在立即退出,隧道也是如此。

\n

SSH 提到-f应该启用某种后台模式,但ssh -fnN也没有这样做;ssh仍然立即退出。

\n

如果我不能拥有好的东西,也许我可以用一个即使没有 STDIN 也能永远运行的命令来近似它们。服务器故障提示:

\n
laptop$ ssh machine -nLN 4040:localhost:4040 &\nlaptop$Job 1, \'ssh machine -nNL 40\xe2\x80\xa6\' has ended\n
Run Code Online (Sandbox Code Playgroud)\n

还是不行?!美好的:

\n
laptop$ ssh machine -nL 4040:localhost:4040 tail -f /dev/null &\nlaptop$\n
Run Code Online (Sandbox Code Playgroud)\n

这似乎在一个微小过程的低、低成本下工作,远景比我在写这个问题时尝试过的其他迭代更好,主要涉及yes......

\n

然而,有没有一种...不太笨拙的方法来在后台运行 SSH 隧道?加分点:我也需要它在 OSX 笔记本电脑上工作......

\n

Pra*_*tne 10

我个人会在系统上创建一个文件,使用控制套接字绑定到隧道-S。当然比处理 PID 更容易。

开放式隧道

ssh -M -S ~/jupyter-tunnel -o "ExitOnForwardFailure yes" -fN machine -L 4040:localhost:4040
Run Code Online (Sandbox Code Playgroud)

关闭隧道

ssh -S ~/jupyter-tunnel -O exit machine
Run Code Online (Sandbox Code Playgroud)

  • 对于每个想知道的人:[`-m 将 ssh 客户端置于“主”模式以进行连接共享。多个 -M 选项将 ssh 置于“主”模式,但在每次更改多路复用状态的操作(例如打开新会话)之前需要使用 ssh-askpass(1) 进行确认。具体请参考ssh_config(5)中ControlMaster的说明。`](https://linuxcommand.org/lc3_man_pages/ssh1.html) (3认同)