Search code examples
javamavenauthenticationsmbjcifs

SmbException failed to connect hostname/IP_address throwing with proper credentials in Java


I need to connect to a shared folder with proper user credentials (username, password, domain). Then when I have access to the folder, I need to list the subfolders and files in it.

Im trying with the jcifs.smb.SmbFile class and jcifs.smb.NtlmPasswordAuthentication for the authentication.

My code is the following:

NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domainName", "userName", "password");
SmbFile smbFile = new SmbFile("smb://servername/someFolder", auth);
for (String fileName : smbFile.list()) {
   System.out.println(fileName);
}

I would be able to connect to the server with these credentials, but I'm getting this error:

Exception in thread "main" jcifs.smb.SmbException: Failed to connect: servername/IP_ADDR
jcifs.util.transport.TransportException
java.net.SocketException: Connection reset
    at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
    at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
    at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
    at java.base/java.net.Socket$SocketInputStream.read(Socket.java:981)
...

Anyone has any idea why am I unable to connect?

SmbFile - https://www.jcifs.org/src/docs/api/jcifs/smb/SmbFile.html

NtlmPasswordAuthentication - https://javadoc.io/static/eu.agno3.jcifs/jcifs-ng/2.1.3/jcifs/smb/NtlmPasswordAuthentication.html


Solution

  • I found the solution!

    Because of my OS (Windows 10) I needed to use SMB2 not SMB1 (this is the default).

    Solution:

    1. Open powershell as an administrator
    2. You need to set a property: Set -SmbServerConfiguration -EnableSMB2Protocol $true Optional: I think it isn't necessarry but I turned off the SMB1 protocol wit the

    Set -SmbServerConfiguration -EnableSMB1Protocol $false command.

    Then you can check the properties with: Get -SmbServerConfiguration command, and be sure about that all of the properties have the right value.

    1. Import the proper dependency to the pom.xml:
    <dependency>
        <groupId>eu.agno3.jcifs</groupId>
        <artifactId>jcifs-ng</artifactId>
        <version>2.1.6</version>
    </dependency>
    

    https://github.com/AgNO3/jcifs-ng

    1. Finally the code:
    public static void sendRequest() throws Exception {
            CIFSContext base = SingletonContext.getInstance();
            CIFSContext authed1 = base.withCredentials(new NtlmPasswordAuthentication(base, "domainName",
                    "userName", "password"));
            try (SmbFile f = new SmbFile("smb:\\serverName\folder", authed1)) {
                if (f.exists()) {
                    for (SmbFile file : f.listFiles()) {
                        System.out.println(file.getName());
                    }
                }
            }
        }