检测 Java 应用程序是否以 Windows 管理员身份运行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4350356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:44:00  来源:igfitidea点击:

Detect if Java application was run as a Windows admin

javawindowsadminprivileges

提问by user489041

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

我有一个 Java 应用程序。无论如何,我是否可以判断该进程是否在 Windows 7 上以管理员权限运行。

回答by MyPasswordIsLasercats

I've found a different solution that seems to be platform-independent. It tries to write system-preferences. If that fails, the user might not be an admin.

我找到了一个不同的解决方案,它似乎与平台无关。它尝试编写系统首选项。如果失败,则用户可能不是管理员。

As Tomá? Zatosuggested, you might want to suppress error messages caused by this method. You can do this by setting System.err:

作为托玛?Zato建议,您可能希望抑制此方法引起的错误消息。您可以通过设置来做到这一点System.err

import java.io.OutputStream;
import java.io.PrintStream;
import java.util.prefs.Preferences;

import static java.lang.System.setErr;
import static java.util.prefs.Preferences.systemRoot;

public class AdministratorChecker
{
    public static final boolean IS_RUNNING_AS_ADMINISTRATOR;

    static
    {
        IS_RUNNING_AS_ADMINISTRATOR = isRunningAsAdministrator();
    }

    private static boolean isRunningAsAdministrator()
    {
        Preferences preferences = systemRoot();

        synchronized (System.err)
        {
            setErr(new PrintStream(new OutputStream()
            {
                @Override
                public void write(int b)
                {
                }
            }));

            try
            {
                preferences.put("foo", "bar"); // SecurityException on Windows
                preferences.remove("foo");
                preferences.flush(); // BackingStoreException on Linux
                return true;
            } catch (Exception exception)
            {
                return false;
            } finally
            {
                setErr(System.err);
            }
        }
    }
}

回答by Codemwnci

I found this code snippet online, that I think will do the job for you.

我在网上找到了这个代码片段,我认为它可以为你完成这项工作。

public static boolean isAdmin() {
    String groups[] = (new com.sun.security.auth.module.NTSystem()).getGroupIDs();
    for (String group : groups) {
        if (group.equals("S-1-5-32-544"))
            return true;
    }
    return false;
}

It ONLY works on windows, and comes built in to the core Java package. I just tested this code and it does work. It surprised me, but it does.

它仅适用于 Windows,并内置于核心 Java 包中。我刚刚测试了这段代码,它确实有效。这让我很惊讶,但确实如此。

The SID S-1-5-32-544 is the id of the Administrator group in the Windows operating system.

SID S-1-5-32-544 是 Windows 操作系统中管理员组的 ID。

Here is the linkfor more details of how it works.

这是有关其工作原理的更多详细信息的链接

回答by Thorbj?rn Ravn Andersen

There is not such a facility available in the Java Runtime Environment, but might be in a platform-dependent native routine. Note that usually the best way to be certain is to actually try to do it, and see if it fails.

Java 运行时环境中没有这样的工具可用,但可能存在于依赖于平台的本机例程中。请注意,通常确定的最好方法是实际尝试这样做,然后看看它是否会失败。

回答by bmargulies

Only by attempting an operation which requires such access (like binding a low-numbered port, or opening a known-to-be-protected file).

仅通过尝试需要此类访问的操作(例如绑定低编号端口或打开已知受保护的文件)。

回答by Alex Fedulov

The method from the answer marked best worked nicely for me until the point when I had to build the code in Jenkins on a Linux machine. com.sun.security.auth.module.NTSystem() is not available there and using sun packages is generally considered a bad practice: link

答案中标记为最佳的方法对我来说效果很好,直到我不得不在 Linux 机器上的 Jenkins 中构建代码。com.sun.security.auth.module.NTSystem() 在那里不可用,使用 sun 包通常被认为是一种不好的做法: 链接

回答by OnSN

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

这是 Windows 10 上的解决方案,我猜它也可以在其他 Windows 操作系统上正常运行。

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;
    }
}

回答by Vinayagam.D

Below code worked out for me

下面的代码对我有用

Command prompt command

命令提示符命令

net user

Java code

Java代码

public static  boolean isAdmin() {
        StringBuilder outputbuilder = new StringBuilder();
    try {
        ProcessBuilder builder = new ProcessBuilder(
                "cmd.exe","/c" ,"net user");
        builder.redirectErrorStream(true);
        Process p = builder.start();
        BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while (true) {
            line = r.readLine();
            if (line == null) { break; }
            outputbuilder.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    System.out.println(outputbuilder.toString());
    return outputbuilder.toString().contains("Administrator");
}

回答by Goran Jovic

Or you could do this:

或者你可以这样做:

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

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.

当我像我一样运行它时,我得到“goran”,当我用 sudo 运行它时,我得到“root”。适用于 Linux。大概需要什么。