Security

在 ControlMaster SSH 會話中以程式方式添加埠轉發

  • December 12, 2012

我剛剛發現了 OpenSSH 的 ControlMaster/ControlPath 功能,它允許您使用單個 SSH 連接來執行多個終端。

由於我經常使用 SSH 來使用埠轉發來獲得加密和經過身份驗證的 VNC 會話,我立即意識到您無法將埠轉發添加到您已經建立連接的遠端伺服器。這很糟糕。

有時後來我發現你可以通過在執行的 SSH 終端會話中鍵入 ~C 來規避這個限制。這將打開一個命令行,允許您添加或刪除埠轉發。

我現在的問題是:如何在使用 ControlMaster/ControlPath 功能的現有 SSH 會話上添加埠轉發,而無需訪問該 SSH 會話中的終端會話。我需要這個來啟用我的腳本,該腳本啟動一個安全的隧道 VNC 連接,以便我添加並稍後刪除其埠轉發。

(我知道我可以使用終端多路復用器,例如 GNU Screen 或 tmux,實際上我已經這樣做了。但出於幾個原因,我喜歡只使用一個 SSH 會話的想法。)

實際上,這很簡單。只需將 ctl_cmd 添加-O forward到您現有的命令中,因此:

ssh -M -L5555:localhost:22 remotehost

變成:

ssh -O forward -M -L5555:localhost:22 remotehost

ssh手冊頁討論了該選項-O ctl_cmd

-O ctl_cmd
       Control an active connection multiplexing master process.  When the -O option is
       specified, the ctl_cmd argument is interpreted and passed to the master process.
       Valid commands are: “check” (check that the master process is running), “forward”
       (request forwardings without command execution), “exit” (request the master to
       exit), and “stop” (request the master to stop accepting further multiplexing
       requests).

當然,這假設您已ControlMaster yes~/ssh/config文件或-M命令行中啟用。

引用自:https://serverfault.com/questions/237688