Подтвердить что ты не робот

Доступ к файлу с использованием Java с Samba JCIFS

У меня вопрос о доступе к файлу с Samba JCIFS. Таким образом, есть сервер, к которому я хочу получить доступ, позвоните ему server.unv.edu, а рабочая группа - WKGRP. на этом сервере есть доля:\\server.unv.edu\pcb $

способ доступа к серверу:

public class SMBAuthenticator extends NtlmAuthenticator{

private String username = "username";
private String password = "password";
private String domain = "smb://server.unv.edu/WKGRP/";

public SMBAuthenticator(){
    NtlmAuthenticator.setDefault(this);
}

и

public class SMBConnection{

public String urlString = "smb://server.unv.edu/pcb$/path/file.txt";
NtlmPasswordAuthentication auth;
SmbFile smbFile;

public SMBConnection() throws MalformedURLException{;
    //url = new URL(urlString);
    SMBAuthenticator authenticator = new SMBAuthenticator();
    auth = authenticator.getNtlmPasswordAuthentication();   
    smbFile = new SmbFile(urlString, auth);
}

public InputStream getSMBInputStream() throws IOException{
    return this.smbFile.getInputStream();
}

public InputStream getInputStream() throws IOException{
    InputStream is = this.getSMBInputStream();
    return is;
}
}

но это не работает. И я получил ошибку

jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:544)
at jcifs.smb.SmbTransport.send(SmbTransport.java:661)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:390)
at jcifs.smb.SmbSession.send(SmbSession.java:218)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:176)
at jcifs.smb.SmbFile.doConnect(SmbFile.java:929)
at jcifs.smb.SmbFile.connect(SmbFile.java:954)
at jcifs.smb.SmbFile.connect0(SmbFile.java:880)
at jcifs.smb.SmbFile.open0(SmbFile.java:972)
at jcifs.smb.SmbFile.open(SmbFile.java:1006)
at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:73)
at jcifs.smb.SmbFileInputStream.<init>(SmbFileInputStream.java:65)
at jcifs.smb.SmbFile.getInputStream(SmbFile.java:2844)
at edu.umd.lib.sambaConnection.SMBConnection.getSMBInputStream(SMBConnection.java:33)
at edu.umd.lib.sambaConnection.SMBConnection.getInputStream(SMBConnection.java:37)
at edu.umd.lib.sambaConnection.SambaConnectionTest.test(SambaConnectionTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

Может ли кто-нибудь дать мне предложение или правильность моего кода, чтобы помочь мне получить доступ к файлу?

Большое вам спасибо.

4b9b3361

Ответ 1

Вы делаете это сложнее, чем должно быть. Следуйте приведенным ниже инструкциям и убедитесь, что общая папка, которую вы создаете, имеет доступ на запись для этого пользователя, который вы используете.

  • загрузите файл jar http://jcifs.samba.org/ (есть только один файл jar)
  • скопируйте и вставьте приведенный ниже код с информацией для имени пользователя, пароля и общей папки и что все, что вам нужно

Я запускал это в Linux и хотел записать в окно Windows, поэтому вы хотите создать общую папку и поместить имя общей папки в следующую переменную если вы не знаете, как создать общую папку в Windows... используйте google как всегда

    String user = "your_user_name";
    String pass ="your_pass_word";

    String sharedFolder="shared";
    String path="smb://ip_address/"+sharedFolder+"/test.txt";
    NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",user, pass);
    SmbFile smbFile = new SmbFile(path,auth);
    SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
    smbfos.write("testing....and writing to a file".getBytes());
    System.out.println("completed ...nice !");

Ответ 2

/** You can simply use this util class for read write operations. **/
package com.wellsfargo.trust.tds.service.trustasset.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;

public class NDMUtil {

public static void writeToNDM(String userName, String password, String domain, String sharedPath,
        String textToWrite) throws MalformedURLException, SmbException, UnknownHostException, IOException {
    NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(domain, userName, password);
    try (OutputStream out = new SmbFileOutputStream(new SmbFile(sharedPath, authentication))) {
        byte[] bytesToWrite = textToWrite.getBytes();
        if (out != null && bytesToWrite != null && bytesToWrite.length > 0) {
            out.write(bytesToWrite);
        }
    }
    ;
}

public static String readFromNDM(String userName, String password, String domain, String sharedPath)
        throws MalformedURLException, SmbException, IOException {
    NtlmPasswordAuthentication authentication = new NtlmPasswordAuthentication(domain, userName, password);
    String fileContent = IOUtil.toString(new SmbFileInputStream(new SmbFile(sharedPath, authentication)),
            StandardCharsets.UTF_8.name());
    System.out.println(fileContent);
    return fileContent;
}

}