Using Java, How can I get a list of all local users on a windows machine

前端 未结 4 1305
你的背包
你的背包 2020-12-21 18:17

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

4条回答
  •  萌比男神i
    2020-12-21 18:51

    There is a simpler solution for what I needed.
    This implementation will use the "net user" 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 user" 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.

提交回复
热议问题