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

2022-09-02 05:05:52

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


答案 1

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

正如Tomáš 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);
            }
        }
    }
}

答案 2

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

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

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

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

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


推荐