繁体   English   中英

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

[英]Detect if Java application was run as a Windows admin

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

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

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

我在网上找到了此代码段,我认为它将为您完成这项工作。

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操作系统中Administrator组的ID。

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

Java Runtime Environment中没有这样的工具,但是可能在依赖于平台的本机例程中。 请注意,通常最好的确定方法是实际尝试执行此操作,然后查看它是否失败。

仅尝试进行需要这种访问的操作(例如,绑定一个低号的端口或打开一个已知的受保护文件)。

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

或者您可以这样做:

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

并查看哪个用户启动了该过程。

当我像我一样运行它时,我会得到“ goran”,当我用sudo运行它时,我会得到“ root”。 在Linux上工作。 大概需要什么。

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

下面的代码为我解决了

命令提示符命令

net user

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM