How can I list all the local users configured on a windows machine (Win2000+) using java.
I would prefer doing this with ought using any java 2 com bridges, or any other third party library if possible.
Preferable some native method to Java.
views:
1194answers:
2Using a Java-COM Bridge , like Jacob. You then select an appropriate COM library, e.g. COM API for WMI to list local users, or any other Windows management information.
The Win32_SystemUsers association WMI class relates a computer system and a user account on that system.
The Win32_Account abstract WMI class contains information about user accounts and group accounts known to the computer system running Windows. User or group names recognized by a Windows NT domain are descendants (or members) of this class.
There is a simpler solution for what I needed.
This implementation will use the "net use" command to get the list of all users on a machine. This command has some formatting which in my case I don't care about, I only care if my user is in the list or not. If some one needs the actual user list, he can parse the output format of "net use" to extract the list without the junk headers and footers generated by "net use"
private boolean isUserPresent() {
//Load user list
ProcessBuilder processBuilder = new ProcessBuilder("net","user");
processBuilder.redirectErrorStream(true);
String output = runProcessAndReturnOutput(processBuilder);
//Check if user is in list
//We assume the output to be a list of users with the net user
//Remove long space sequences
output = output.replaceAll("\\s+", " ").toLowerCase();
//Locate user name in resulting list
String[] tokens = output.split(" ");
Arrays.sort(tokens);
if (Arrays.binarySearch(tokens, "SomeUserName".toLowerCase()) >= 0){
//We found the user name
return true;
}
return false;
}
The method runProcessAndReturnOutput runs the process, collects the stdout and stderr of the process and returns it to the caller.