SmbException 无法使用 Java 中的正确凭据连接主机名/IP_address 抛出

问题描述

我需要使用正确的用户凭据(用户名、密码、域)连接到共享文件夹。 然后当我可以访问该文件夹时,我需要列出其中的子文件夹和文件

我正在尝试使用 jcifs.smb.SmbFile 类和 jcifs.smb.NtlmPasswordAuthentication 进行身份验证。

我的代码如下:

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

我可以使用这些凭据连接到服务器,但出现此错误

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)
...

有人知道为什么我无法连接吗?

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

解决方法

我找到了解决方案!

由于我的操作系统 (Windows 10),我需要使用 SMB2 而不是 SMB1(这是默认设置)。

解决方案:

  1. 以管理员身份打开 powershell
  2. 您需要设置一个属性:Set -SmbServerConfiguration -EnableSMB2Protocol $true 可选:我认为这不是 necessarry 但我关闭了 SMB1 协议机智

Set -SmbServerConfiguration -EnableSMB1Protocol $false 命令。

然后您可以使用:Get -SmbServerConfiguration 命令检查属性,并确保所有属性都具有正确的值。

  1. 将适当的依赖项导入到 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. 最后是代码:
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());
                }
            }
        }
    }