Detect if Java application was run as a Windows admin

家住魔仙堡 提交于 2019-11-26 16:22:57

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.

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

Here is the link for more details of how it works.

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áš Zato suggested, you might want to suppress error messages caused by this method. You can do this by setting 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);
            }
        }
    }
}

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.

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

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

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.

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

Below code worked out for me

Command prompt command

net user

Java code

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");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!