缘由

一些远程服务器可能无法直接访问,或存在本地访问连接性能差,而需要使用跳板机的需求。

这里不使用 SSH 默认支持的跳板(jump)特性,纯粹使用指定代理服务器作为前置进行远程服务器的连接。

依赖

  • netcat

注意,这里的 netcat 为 openbsd 版本,其他版本可能不支持 -X 参数。

步骤

选择代理服务类型

netcat manual 中写道 ”-X proxy_protocol Use proxy_protocol when talking to the proxy server. Supported protocols are 4 (SOCKS v.4), 5 (SOCKS v.5) and connect (HTTPS proxy). If the protocol is not specified, SOCKS version 5 is used.”

由此我们可以使用 socks4、socks5、https类型的代理服务,对应的 -X 参数为 4、5、connect,请根据你使用代理服务类型修改参数。

修改 SSH 配置

默认 SSH 配置文件路径为 ~/.ssh/config,这里以 Github 为例。

增加以下代码至配置文件。

# ~/.ssh/config
Host github.com
    HostName github.com
    User git
    ProxyCommand nc -X 5 -x 10.0.0.1:1080 %h %pCode language: PHP (php)

其中,我们使用 HostName 匹配主机名为 “github.com” ,用 User 匹配连接时使用用户名为 git 的用户 ,在 ProxyCommand 指定使用 netcat 作为代理隧道。netcat 参数中 -X 5 为指定代理服务类型为 socks5, -x 指定代理服务器地址,%h 为主机名,%p 为端口。

连接验证

使用 SSH 连接至你的远程服务器,追加 -v 参数以观察日志。

ssh user@example.com -vCode language: CSS (css)

观察 ProxyCommand 是否生效。

# SSH logsdebug1: Executing proxy command: exec nc -X 5 -x 10.0.0.1:1080 github.com 22
…Code language: CSS (css)

若出现与上述类似的日志,则表明配置已生效。

大功告成

现在连接到与配置匹配的主机时,都将会使用 netcat 作为代理隧道。

Reference


了解 Starx's Home 的更多信息

订阅后即可通过电子邮件收到最新文章。