SFTP connection with apache vfs fails but is successful with WinSCP

4.8k views Asked by At

I can successfully connect with WinSCP, using given credentials, to SFTP server. But when doing it from java using apache vfs I get error:

Caused by: org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server at "sftp://username:***@server_addres/".   
at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:170)
at org.apache.commons.vfs2.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:97)
...  22 more
Caused by: com.jcraft.jsch.JSchException: Auth fail
at com.jcraft.jsch.Session.connect(Session.java:512)
at com.jcraft.jsch.Session.connect(Session.java:183)
at org.apache.commons.vfs2.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:166)

I have checked credentials and they are exactly same as those when I try to connect with WinSCP. WinSCP can connect successfully, but my java code gets the above error (Auth fail).
Does anybody has some clue what could be the issue?
Public IP range of the machine I am connecting from has been added to firewall exceptions as trusted IP on the other side.
Please help, any ideas are very much appreciated.

Kind regards,
misamas

1

There are 1 answers

0
mismas On

The problem was in the password. It contained % sign which is a special character when passed in URI (like pass%word).
So the solution was doing UriParser.encode(sftpUri) before passing it to manager.resolveFile() method like this (in order to replace % sign of password in URI with its hex code %25):

import org.apache.commons.vfs2.provider.UriParser;
...
String sftpUri = String.format("sftp://%s:%s@%s/%s/%s", configData.getUserId(), configData.getPassword(), configData.getServerAddress(),
                configData.getRemoteDirectory(), configData.getFileName());
String sftpUriEncoded = UriParser.encode(sftpUri);
FileObject remoteFile = manager.resolveFile(sftpUriEncoded, options);