在 ControlMaster SSH 会话上以编程方式删除端口转发

aef*_*aef 5 security ssh port-forwarding multiplexing

不久前,我得到了一个答案,告诉我如何在正在运行的 SSH ControlMaster 进程上添加端口转发。要知道这有很大帮助,但是在我不再需要之后,我仍然缺少删除此类端口转发的方法。

据我所知,您可以通过正常连接上的内部命令键序列来执行此操作,这似乎对 ControlMaster 客户端禁用。即使这是可能的,我也需要一个可以用脚本自动化的解决方案,这肯定不是那么容易。

有没有办法做到这一点?它是否易于自动化?

acu*_*ich 6

正如我以前的答复便签,SSH手册页解释了-O ctl_cmd详细,这里ctl_cmd是一个checkforwardcancel,或exit

-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).
Run Code Online (Sandbox Code Playgroud)

您可以使用ctl_cmd's 来完成您想要的脚本自动化。您需要首先ControlMaster使用-S类似的方式创建一个套接字并通过 ssh 连接到远程主机,如下所示:

ssh -v -M -S/tmp/controlmaster-remotehost remotehost
Run Code Online (Sandbox Code Playgroud)

然后从你的本地机器你可以forwardcancel你喜欢的端口。您可以使用一个命令转发多个端口:

ssh -O forward -S/tmp/controlmaster-remotehost -L5555:localhost:22 -L3333:localhost:22 remotehost
Run Code Online (Sandbox Code Playgroud)

和/或一次处理一个:

ssh -O cancel  -S/tmp/controlmaster-remotehost -L5555:localhost:22 remotehost
ssh -O cancel  -S/tmp/controlmaster-remotehost -L3333:localhost:22 remotehost
Run Code Online (Sandbox Code Playgroud)

我创建了一个带有并排会话要点,显示了ssh -O ctl_cmd正在运行的内容;左侧是来自localhost的端口forward/ cancel,右侧是连接到remotehost的ssh输出:

https://gist.github.com/raw/4265549/999d90b8f85190a41eed00e4d60d5d22da6c67b9/ssh-controlmaster-side-by-side.log

这些命令仅从OpenSSH 6.0 开始可用:

 * ssh(1): support for cancelling local and remote port forwards via the
   multiplex socket. Use ssh -O cancel -L xx:xx:xx -R yy:yy:yy user@host"
   to request the cancellation of the specified forwardings
 * support cancellation of local/dynamic forwardings from ~C commandline
Run Code Online (Sandbox Code Playgroud)

如果您有早期版本,则需要升级。如果您使用的是 Mac OS X,则可以安装 macports,然后使用以下命令升级sudo port install openssh这会将其安装到/opt/local/bin.