Detect if Java application was run as a Windows admin

前端 未结 8 2072
天命终不由人
天命终不由人 2020-11-27 05:37

I have a Java application. Is there anyway I can tell if the process was run with admin privileges, on Windows 7.

8条回答
  •  粉色の甜心
    2020-11-27 06:04

    Here is a solution on Windows 10, I guess that it runs properly on other Windows OS too.

    public static boolean isAdmin() {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe");
            Process process = processBuilder.start();
            PrintStream printStream = new PrintStream(process.getOutputStream(), true);
            Scanner scanner = new Scanner(process.getInputStream());
            printStream.println("@echo off");
            printStream.println(">nul 2>&1 \"%SYSTEMROOT%\\system32\\cacls.exe\" \"%SYSTEMROOT%\\system32\\config\\system\"");
            printStream.println("echo %errorlevel%");
    
            boolean printedErrorlevel = false;
            while (true) {
                String nextLine = scanner.nextLine();
                if (printedErrorlevel) {
                    int errorlevel = Integer.parseInt(nextLine);
                    return errorlevel == 0;
                } else if (nextLine.equals("echo %errorlevel%")) {
                    printedErrorlevel = true;
                }
            }
        } catch (IOException e) {
            return false;
        }
    }
    

提交回复
热议问题