I have a Java application. Is there anyway I can tell if the process was run with admin privileges, on Windows 7.
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.
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);
}
}
}
}
Kvě 07, 2015 1:49:14 ODP. java.util.prefs.WindowsPreferences <init> WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
Is it possible to surpress these? –
Booker NullPointerException
, due to System.setErr(null)
. To fix that, use a dummy output stream instead: System.setErr(new PrintStream(new OutputStream() { @Override public void write(int i) throws IOException { } }));
–
Transvalue synchronized(systemErr)
has no effect if the other Threads doesn't synchronize to System.err
too. –
Slesvig Run as Administrator
, which is different than just running a program as a user who is part of the administrators group. –
Trifoliate OutputStream
has a built-in static method to create a "null output stream", though, accessed via nullOutputStream()
. That one works. Maybe it's because a different overload for write()
is called on it, while this answer only overrides one of them. The built-in null stream one overrides all of them. –
Discourse System.err
also didn't work for me. I think setErr()
already sets a new "standard" output stream? So System.err
after that just refers to our "null stream" again. Saving the current System.err
stream in a variable before calling setErr()
, and then setting it back to that in the finally {}
block, worked for me. –
Discourse 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.
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
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");
}
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.
System.out.println(System.getenv());
Maybe, there is something else. –
Poisoning System.out.println(System.getProperties());
–
Poisoning © 2022 - 2024 — McMap. All rights reserved.