SFTP Connect在测试中使用60秒

时间:2018-08-14 13:11:05

标签: java ssh sftp apache-commons

我运行一些尝试使用Apache Commons VFS库连接到SFTP服务器的测试时遇到问题。测试正在代理后面的计算机上运行,​​并且SFTP服务器不在同一网络上。当运行下面的testSshClient()方法时,从connect()方法开始需要60秒,而如果我尝试使用Filezilla进行连接,它将立即连接。

我知道以下方法实际上有效,因为我设法成功地使用它传输了文件,但是我需要摆脱延迟。

private boolean testSshClient(Map<String, String> hostConfig) {
    SshClient client = new VfsSftpClient();
    String strictChostKeyCheck = "no";

    SftpClientConfig config = new SftpClientConfig();

    client.authUserPassword(hostConfig.get("username"), hostConfig.get("password"));
    client.setHostsKeyChecking(hostConfig.get("strictHostKeyChecking"));
    try {
        long start = System.currentTimeMillis();
        System.out.println("starting connect");
        client.connect(hostConfig.get("host"));
        long timeInSeconds = (System.currentTimeMillis() - start) / 1000;
        System.out.println("connected using " + timeInSeconds +
                " seconds" +
                "\nstarting disconnect");
        client.disconnect();
    } catch (IOException e) {

        e.printStackTrace();
        return false;
    }
    return true;
}


//Connect method
public void connect(String host) throws IOException {
    initFileSystemManager();
    FileSystemOptions connectionOptions = buildConnectionOptions();
    String connectionUrl = buildConnectionUrl(host);
    remoteRootDirectory = fileSystemManager.resolveFile(connectionUrl, connectionOptions);
}

// buildConnectionOptions method
private FileSystemOptions buildConnectionOptions() throws FileSystemException {
    SftpFileSystemConfigBuilder sftpConfigBuilder = SftpFileSystemConfigBuilder.getInstance();
    FileSystemOptions opts = new FileSystemOptions();

    sftpConfigBuilder.setProxyHost(opts, "some_proxy_address");
    sftpConfigBuilder.setProxyPort(opts, 8080);
    sftpConfigBuilder.setProxyType(opts, SftpFileSystemConfigBuilder.PROXY_HTTP);

    sftpConfigBuilder.setUserDirIsRoot(opts, false);
    sftpConfigBuilder.setStrictHostKeyChecking(opts, getHostsKeyChecking());
    if (knownHosts != null) {
        sftpConfigBuilder.setKnownHosts(opts, knownHosts.toFile());
    } 
    else {
        sftpConfigBuilder.setKnownHosts(opts, new File(".ssh/known_hosts"));
    }
    if (privateKey != null) {
        sftpConfigBuilder.setIdentities(opts, new File[] { privateKey.toFile() });
    }
    return opts;
}

我还尝试过这样设置代理:

System.setProperty("http.proxyHost", "some_proxy_address");
System.setProperty("http.proxyPort", "8080");

虽然在buildConnectionOptions()方法中删除了代理配置,但只会导致以下异常:

org.apache.commons.vfs2.FileSystemException    
Caused by: com.jcraft.jsch.JSchException: Session.connect: java.net.SocketTimeoutException: Read timed out

一个附带的问题是,像这样定义代理有什么区别?

0 个答案:

没有答案