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();
}
}
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With