I have tried the below code:
String url = "smb://remotehost/SharedPath/Comp/NG/";
NtlmPasswordAuthentication auth2 = new
NtlmPasswordAuthentication(null,"user", "password");
SmbFile dir = new SmbFile(url, auth);
for (SmbFile f : dir.listFiles())
{
if(f.getName().contains("Test")) //successfully reads the file
{
System.out.println("test...."+f);
filename= f.getUncPath();
System.out.println("filename...."+filename);
sftpChannel.put(filename, remoteDirectory); // throws exception
}
}
Above code results in exception as follows:
java.io.FileNotFoundException: \\remotehost\SharedPath\comp\NG\Test.txt (Logon failure: unknown user name or bad password)
Please note:
I am able to read the files present in the remote server using the above code but not able to copy or transfer the file from remote server path to Linux server path.
As the connection to remote server and linux server was successful, I tried to directly copy the file from remote path to linux server path using sftpchannel.put()
but it throws exception.
Once connected using smb, will we not be able to connect directly to shared path using below url? String url = "//remotehost/SharedPath/Comp/NG/";
Please note: I am connecting to Linux server using jsch library and I am able to successfully connect to Linux server using sftpChannel.connect(); and also able to put the file from my local machine to Linux server using sftpChannel.put(localpath, linuxpath); and To connect to windows server I am using smbFile. I am able to connect but not able to copy the file from windows to Linux server path. I tried using sftpChannel.put(filename, remoteDirectory); for the same but it resulted in exception. At this particular step I assumed that as the connection to windows server is successful I will be able to copy the files as well. I am able to read the file but not copy. Not sure why this is happening.
Can anyone provide me the proper steps to do this?
I guess the type of sftpChannel
is com.jcraft.jsch.ChannelSftp
. Then the following method will do the copy for you. Of course you have to pass properly initialized SmbFile
and ChannelSftp
objects as parameters.
public void copyFromSmbToSftp(SmbFile smbFile, ChannelSftp channelSftp, String destPath) throws IOException, SftpException {
try(BufferedInputStream inputStream = new BufferedInputStream(smbFile.getInputStream());
BufferedOutputStream outputStream = new BufferedOutputStream(channelSftp.put(destPath))){
byte[] buffer = new byte[64*1024];
int bytesRead;
while((bytesRead=inputStream.read(buffer, 0, buffer.length))!=-1){
outputStream.write(buffer, 0, bytesRead);
}
}
}