Ⅰ.背景

      在开发的过程中,遇到这样的需求:生产环境上系统需要访问外部系统的SFTP服务器,也就是说内网服务器需要访问外网的服务器,这时需要一台跳板机来充当一个中转连接的角色。在一番谷歌之后,找到了corkscrew,这个工具可以透过代理连接SSH,当然也能代理SFTP咯!折腾一番之后未果发现一个更简单的方法,遂弃😂,原来JSCH本来就支持代理连接的!不仅支持HTTP,还支持SOCKET代理!

Ⅱ.代码

    private void proxyConnect() throws Exception {
        disconnect();

        JSch jsch = new JSch();

        if (!Strings.isNullOrEmpty(this.prikey)) {
            if (Strings.isNullOrEmpty(this.phrase)) {
                jsch.addIdentity(this.prikey);
            } else {
                jsch.addIdentity(this.prikey, this.phrase);
            }
        }

        Session session = jsch.getSession(this.user, this.host, this.port);
        session.setProxy(new ProxyHTTP(proxyHost, proxyPort));//核心代码

        if (!Strings.isNullOrEmpty(this.passwd)) {
            session.setPassword(this.passwd);
        }

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setTimeout(this.timeout);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        this.cs = (ChannelSftp) channel;
    }

      从上面代码看出,只是比普通的SFTP连接的代码多了一行,并且多了代理IP和端口。

Ⅲ.代理服务器

      在跳板机服务器上面安装Apache Httpd,安装完成之后编辑httpd.conf文件。

AllowCONNECT 443 563 22  #连接的SFTP端口号加入到这里面 SFTP端口号默认是22
ProxyRequests On

      接下来启动Apache,测试一下效果把!😀