I have a Java application. Is there anyway I can tell if the process was run with admin privileges, on Windows 7.
From the Start menu, type cmd in the textbox and when the program cmd.exe appears, right click on it and select Run as Administrator.
Right-click any column header and choose “Select Columns” from the popup menu. Scroll down until you see the Elevated option, check that box and click OK. Now, the Details tab of Task Manager will be showing a new “Elevated” column. You can easily see which process is launched with admin/elevated privileges.
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);
}
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With