jcifs.smb.SmbException: The network name cannot be found - java

The following is my piece of code
SmbFile catalExp = new SmbFile("smb://<Shared machine name>/Project share/Home/4. Folders/planning - Design & Exec/sample.txt",
new NtlmPasswordAuthentication(LoadProp.getShrdDomain(),"user","paswd"));
In this i am getting the error
jcifs.smb.SmbException: The network name cannot be found
at jcifs.smb.SmbTransport.send(SmbTransport.java:753)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:140)
at jcifs.smb.SmbSession.send(SmbSession.java:103)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:132)
at jcifs.smb.SmbFile.connect(SmbFile.java:674)
at jcifs.smb.SmbFile.connect0(SmbFile.java:644)
at jcifs.smb.SmbFile.open0(SmbFile.java:700)
at jcifs.smb.SmbFile.createNewFile(SmbFile.java:2027)
Is this anything to do with the user rights to that particular shared folder or am I doing anything wrong
Please advice

I ran into this error message, and it turned out the problem was that my network path was incorrect. You'll want to ensure that the NtlmPasswordAuthentication object is configured correctly, that your network path is correct, and that you've set the jcifs.netbios.wins property correctly, as indicated in the first example on this page.
For example, to load a remote properties file:
final NtlmPasswordAuthentication AUTH = new NtlmPasswordAuthentication("domainname", "username", "password");
Config.setProperty("jcifs.netbios.wins", "10.10.1.1");
Properties props = new Properties();
InputStream in = new SmbFileInputStream(new SmbFile("smb://10.10.1.1:445/rootfolder/path/filename.properties", AUTH));
props.load(in);
(You'll need to add try/catch and input stream closing)
A good way to ensure that all of your parameters are correct is to test logging into and locating the file using a smb/cifs client. For example smbclient on linux/unix:
smbclient -Uusername -p 139 //10.10.1.1/rootfolder
The domain is displayed at the top when you login with smbclient:
Domain=[DOMAINNAME]
..and you can navigate to your file to make sure you've got the path correct.

After running into this issue for almost 1 day i realize that these exception is meaningless
I was just giving wrong path of server side location
Below is the peace of groovy code worked for me
String domain = "domain"
String user = "username"
String pass = "password"
String IP = "xx.yy.zz.aa"
String sharedFolder="//my//path//to//server//";
String path="smb://$IP"+sharedFolder+"test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, 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 !");

Well I'm getting this error also but only on one device, my code that works on Android 4.04 is
String strprog = "STRING CREATED| "; //debug log string
try {
strprog += "NTLM| ";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("username:password");
strprog += "SMB| ";
SmbFile file = new SmbFile("smb://<pcname>/foldername/filename.txt",auth);
strprog += "EXIST| ";
String there = String.valueOf(file.exists());
strprog += "View| ";
TextView pp;
pp = (TextView) findViewById(R.id.tv);
pp.setText(there);
} catch (Exception e) {
// TODO Auto-generated catch block
strprog += "ERROR! ";
TextView ll;
ll = (TextView) findViewById(R.id.tv);
ll.setText(strprog + e.getStackTrace().toString() + " " + e.getMessage() + " " + e.getLocalizedMessage() );
}
The only difference I see is where you have your NtlmPasswordAuth compared to mine.
But as I stated for some reason this throws null input param on Andriod 2.0 when I dive deeper then smb://host but I hope this helps you out.

I had this problem, and it turned out that I did not see what the share name was that was mapped to my Windows shared drive... So, using Mac OS, I ran:
smbutil view smb://MYUSERNAME#HOSTNAME
After I was prompted for my password, I then was displayed a list of share names (that weren't evident when I looked at this stuff using Windows). Once I found my share name, it was as simple as using that when connecting with JCIFS:
new SmbFile("smb://HOSTNAME/SHARENAME/path/I/was/trying/to/access", auth);

Related

jcifs.smb.SmbAuthException: Logon failure: user not allowed to log on to this computer

Trying to read a file over a Windows in Java using jCIFS library in java.
This section of code was working perfectly fine when the user had the “Logon locally” rights enabled in Windows. However when we implemented the password non-expiry property our server team has disabled the “Logon locally” rights for the user.
Now, when we browsed the path - manually, we are able to access it without any issue.
When application tries to access the path getting below error at app server:
FATAL - jcifs.smb.SmbAuthException: Logon failure: user not allowed to log on to this computer.
FATAL - Error msg: Logon failure: user not allowed to log on to this computer.
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, "domain\\"+this.userName, this.password);
String fileName = "";
String filePath = "";
while (result1.next()) {
for(int i=1; i<=columnsNumber1; i++) {
String name = rsmd1.getColumnName(i);
if(name.equals("FILE_PATH")) {
filePath = result1.getString(i);
} else if (name.equals("PDF_FILE_NAME")) {
fileName = result1.getString(i);
}
}
}
String newFilePath = filePath.replace('\\', '/');
String path = "smb:"+newFilePath+"/Stored/"+fileName;
SmbFile sFile = new SmbFile(path, auth);
try (SmbFileInputStream in = new SmbFileInputStream(sFile)) {
int bytesRead = 0;
do {
bytesRead = in.read(buffer);
}
while (bytesRead > 0);
}
byte[] encoded = Base64.getEncoder().encode(buffer);
Do we have to set particular property for NtlmPasswordAuthentication authentication in this case?
Please do help, got stuck here
I found its solution. Posting it here if it can help others.
Adding two config properties helped - "jcifs.netbios.hostname" and "jcifs.netbios.wins"
Config.setProperty("jcifs.netbios.hostname", Messages.getString("Constants.serverHostName"));
Config.setProperty("jcifs.netbios.wins", Messages.getString("Constants.serverHostName"));
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(null, "edelcap\\"+this.reportUserName, this.reportPassword);

Google drive api to get all children is not working if I dynamically pass fileId to query

I am trying google drive api to search parents of a folder. In search query i have to pass file id dynamically instead of hard coding. I tried below code. but I am getting file not found json response.
here its not taking fileId as value i think its consider as String
if I hardcode the value it is working.
FileList result = service.files().list().setQ("name='testfile' ").execute();
for (com.google.api.services.drive.model.File file : result.getFiles()) {
System.out.printf("Found file: %s (%s)\n",
file.getName(), file.getId());
String fileId =file.getId();
FileList childern = service.files().list().setQ(" + \"file.getId()\" in parents").setFields("files(id, name, modifiedTime, mimeType)").execute();
This should help.
String fileid=file.getId()
service.files().list().setQ("'" + fileId + "'" + " in parents").setFields("files(id, name, modifiedTime, mimeType)").execute();
Make sure you have valid file.getId()
I know your question states java but the only sample of this working is in C#. Another issue is as far as i know PageStreamer.cs does not have an equivalent in the java client library.
I am hoping that C# and java are close enough that this might give you some ideas of how to get it working in Java. My java knowledge is quote basic but i may be able to help you debug it if you want to try to convert this.
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
// Building the initial request.
var request = service.Files.List();
// Applying optional parameters to the request.
request = (FilesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
var pageStreamer = new Google.Apis.Requests.PageStreamer<Google.Apis.Drive.v3.Data.File, FilesResource.ListRequest, Google.Apis.Drive.v3.Data.FileList, string>(
(req, token) => request.PageToken = token,
response => response.NextPageToken,
response => response.Files);
var allFiles = new Google.Apis.Drive.v3.Data.FileList();
allFiles.Files = new List<Google.Apis.Drive.v3.Data.File>();
foreach (var result in pageStreamer.Fetch(request))
{
allFiles.Files.Add(result);
}
return allFiles;
}
catch (Exception Ex)
{
throw new Exception("Request Files.List failed.", Ex);
}

EC2 UserData not working with Java SDK

I am trying to send some userData while spawning a new instance but unfortunately it is not working. The code is:
For debugging purposes, I have just used an echo statement, but I cannot find any new file generated on the machine. I also checked the cloud-init logs in /var/log folder, but none of them are present.
Can anyone help me to figure out a way to debug this problem or is there something crucial that I am missing?
I am using C4.8xLarge instances for the reference.
public static String getUserData() throws UnsupportedEncodingException {
String userData = "";
userData = userData + "#!/bin/bash" + "\n";
userData += "echo hello > hello" + "\n";
String base64UserData = null;
try {
base64UserData = new String(Base64.encodeBase64(userData.getBytes("UTF-8")), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return base64UserData;
}
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.setImageId(AMI_ID);
runInstancesRequest.setEbsOptimized(true);
runInstancesRequest.setInstanceType(INSTANCE_TYPE);
runInstancesRequest.setMinCount(1);
runInstancesRequest.setMaxCount(1);
runInstancesRequest.withSecurityGroups("JavaSecurityGroup1");
runInstancesRequest.withUserData(getUserData());
List<BlockDeviceMapping> map = new ArrayList<>();
map.add(new BlockDeviceMapping().withEbs(new EbsBlockDevice().withSnapshotId("snap-af8s67ef").withIops(9000).withVolumeSize(300).withVolumeType("io1")).withDeviceName("/dev/sdf"));
runInstancesRequest.withBlockDeviceMappings(map);
RunInstancesResult runInsRes = ec2.runInstances(runInstancesRequest);
Thanks!
After creating an instance, go into the EC2 web console and view the user data on the instance. You should be able to view it as plain text in the web console. If it isn't there, or if it contains something other than the two lines you are trying to set as the user data, then you will know there is an issue with the way you are setting the user data.
If it is there and looks correct, then you will need to look into the cloud-init service log /var/log/cloud-init-output.log on the created instance to see what the error is.
Edit: I just noticed you said the cloud-init logs are not present on the machine. What OS are you using for this server? It may not have the cloud-init service.

Dropbox Core API JAVA Authorization Code

Using the dropbox core api tutorial I am able to upload a file.
However, my question is an exact replica of this SO post--- That is, once I have my authorization code and comment out the user auth lines so that I dont have to manually re-authorize approval every time I use dropbox I get the following errors:
Exception in thread "main" com.dropbox.core.DbxException$BadRequest: {"error_description": "code has already been used", "error": "invalid_grant"}
OR
Exception in thread "main" com.dropbox.core.DbxException$BadRequest: {"error_description": "code has expired (within the last hour)", "error": "invalid_grant"}
I am positive I have the correct authorization code.
I hope that I'm missing something, else whats the point of an API if you have to induce manual intervention every time you use it?
Edit: My Exact Code (keys have been scrambled)
import com.dropbox.core.*;
import java.io.*;
import java.util.Locale;
public class DropboxUpload {
public static void main(String[] args) throws IOException, DbxException {
// Get your app key and secret from the Dropbox developers website.
final String APP_KEY = "2po9b49whx74h67";
final String APP_SECRET = "m98f734hnr92kmh";
DbxAppInfo appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);
DbxRequestConfig config = new DbxRequestConfig("JavaTutorial/1.0",
Locale.getDefault().toString());
DbxWebAuthNoRedirect webAuth = new DbxWebAuthNoRedirect(config, appInfo);
// Have the user sign in and authorize your app.
//String authorizeUrl = webAuth.start();
//System.out.println("1. Go to: " + authorizeUrl);
//System.out.println("2. Click \"Allow\" (you might have to log in first)");
//System.out.println("3. Copy the authorization code.");
//String code = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
DbxAuthFinish authFinish = webAuth.finish("VtwxzitUoI8DDDLx0PlLut5Gjpw3");
String accessToken = authFinish.accessToken;
DbxClient client = new DbxClient(config, accessToken);
System.out.println("Linked account: " + client.getAccountInfo().displayName);
File inputFile = new File("/home/dropboxuser/Documents/test.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = client.uploadFile("/Public/test.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
DbxEntry.WithChildren listing = client.getMetadataWithChildren("/");
System.out.println("Files in the root path:");
for (DbxEntry child : listing.children) {
System.out.println(" " + child.name + ": " + child.toString());
}
FileOutputStream outputStream = new FileOutputStream("test.txt");
try {
DbxEntry.File downloadedFile = client.getFile("/Public/test.txt", null,
outputStream);
System.out.println("Metadata: " + downloadedFile.toString());
} finally {
outputStream.close();
}
}
}
You should be storing and reusing the access token, not the authorization code.
So after doing this once:
String accessToken = authFinish.accessToken;
You should just replace the whole thing with
String accessToken = "<the one you already got>";
BTW, if you just need an access token for your own account, you can generate one with the click of a button! See https://www.dropbox.com/developers/blog/94/generate-an-access-token-for-your-own-account.

Connecting to PC to view shared folders from Android device

I am working on a samba client for Android. Given an IP address it should connect to it and browse the shared folders.
For this I use JCIFS. I dropped the jar in my Android project and added following code to connect to PC and get the list of files:
private void connectToPC() throws IOException {
String ip = "x.x.x.x";
String user = Constants.username + ":" + Constants.password;
String url = "smb://" + ip;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
SmbFile root= new SmbFile(url, auth);
String[] files = root.list();
for (String fileName : files) {
Log.d("GREC", "File: " + fileName);
}
}
And I get in return: jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad password.
But the credentials are correct. I also tried with another samba client from the android market that uses JCIFS and it successfully connected to that ip, so obviously I am doing something wrong here but don't know what especially.
Any help is highly appreciated.
In the end I managed successfully to connect to PC. The issue turned out to be in the NtlmPasswordAuthentication(); constructor.
So, instead of this:
String user = Constants.username + ":" + Constants.password;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
I changed to this:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
Constants.username, Constants.password);
I don't know why, perhaps it's because of ":" special character, perhaps because of Android, but passing an empty domain name, the user name, and password separately to the constructor, solved the issue.
Since some people will get to this topic if they got a similar problem with android and JCIFS,
these are other common problems when trying to make it work:
*Put the .jar specifically in /libs folder of your android project (not just via "build path")
*Be sure that your project has internet permission What permission do I need to access Internet from an android application?
*Also be sure that your JCIFS code is running in a separate thread from the UI (in other words, use AsyncTask class) how to use method in AsyncTask in android?
*Code:
protected String doInBackground(String... params) {
SmbFile[] domains;
String username = USERNAME;
String password = PASSWORD;
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
username, password);
try {
SmbFile sm = new SmbFile(SMB_URL, auth);
domains = sm.listFiles();
for (int i = 0; i < domains.length; i++) {
SmbFile[] servers = domains[i].listFiles();
for (int j = 0; j < servers.length; j++) {
Log.w(" Files ", "\t"+servers[j]);
}
}
} catch (SmbException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return "";
}
these were the problems i encounter while trying to make work JCIFS on android, hope to help anyone, regards.
maybe i can help other people too.
I had the problem that i used thread.run() instead of thread.start() to execute the Smb-Code in a Runnable. I searched a lot of time for an answer but nothing fixed my problem.
But then a friend explained me the different between thread.run() and thread.start():
run(): Execute the Methode (for example the run() Methode of a Runnable) like a normal Method (synchronous)
start(): Start the Thread with the Runnable in an own task (asynchronous)
And for Smb you need a asynchronous Thread. Because of this you need to call thread.start()!
Maybe someone make the same mistake as i did.

Categories

Resources