smbexception无法使用java中的正确凭据连接主机名/ip_地址

wljmcqd8  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(405)

我需要使用正确的用户凭据(用户名、密码、域)连接到共享文件夹。然后,当我有权访问该文件夹时,我需要列出其中的子文件夹和文件。
我在试着用这个 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)
...

有人知道我为什么无法连接吗?
SMB文件-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

t3psigkw

t3psigkw1#

我找到了解决办法!
由于我的操作系统(windows 10),我需要使用smb2而不是smb1(这是默认设置)。
解决方案:
以管理员身份打开powershell
您需要设置一个属性: Set -SmbServerConfiguration -EnableSMB2Protocol $true 可选:我认为这不是必需的,但我关闭了smb1协议 Set -SmbServerConfiguration -EnableSMB1Protocol $false 指挥部。
然后,您可以使用以下工具检查属性: Get -SmbServerConfiguration 命令,并确保所有属性都具有正确的值。
将适当的依赖项导入pom.xml:

<dependency>
    <groupId>eu.agno3.jcifs</groupId>
    <artifactId>jcifs-ng</artifactId>
    <version>2.1.6</version>
</dependency>

https://github.com/agno3/jcifs-ng
最后,代码:

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());
                }
            }
        }
    }

相关问题