Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSCH: SFTP. Hangs at session.connect() using the port 21

Tags:

java

sftp

jsch

I am connecting to FTP server via sftp(JSCH).

Evertime i connect to the FTP server using the port 21, it always hangs at session.connect().

It does not throw any exception. But when i use other ports. It works and it throws exception.

Is there any way i could catch the error?

Here is a sample of my code.

public static void main(String[] args) throws SftpException {

    JSch jsch = new JSch();

    try {

        Session session = jsch.getSession("username", "host", 21);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword("password");
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        session.disconnect();
        channelSftp.disconnect();

    } catch (JSchException e) {
        log("Cannot make connection to FTP server ");
        e.printStackTrace();

    }

}
like image 475
aeycee Avatar asked Dec 13 '13 05:12

aeycee


2 Answers

I had a similar problem but with the correct port. session.connect() just hangs and does not return anything. While other programs can successfully connect.

The reason was that the host provides more authentication methods, and we must point Jsch to use only password.

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("PreferredAuthentications", "password");
        session.setConfig(config);
like image 108
Michael T Avatar answered Sep 22 '22 01:09

Michael T


Could it be that port 22 is the default port for SFTP? And a FTP server running on port 21 won't know how to negotiate the conversation for secure FTP. Basically, SFTP is FTP over SSH.

EDITED: The issue is, it is waiting indefinitely for the negotiation to complete. It is a Mexican stand-off with neither side giving up. Call session.setTimeout() before session.connect(), or call session.connect(timeout), with some suitable value (3-5 seconds). I believe the timeout is in milliseconds.

like image 32
brettw Avatar answered Sep 19 '22 01:09

brettw