Detect if Java application was run as a Windows admin

前端 未结 8 2065
天命终不由人
天命终不由人 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;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 06:05

    Or you could do this:

    System.getenv().get("USER")

    And see which user started the process.

    When I run it as me I get "goran", when I run it with sudo I get "root". Works on Linux. Probably what was needed.

    0 讨论(0)
提交回复
热议问题