use*_*041 19 java windows privileges admin
我有一个Java应用程序.无论如何,我可以判断该进程是否在Windows 7上以管理员权限运行.
MyP*_*ats 32
我找到了一个似乎与平台无关的不同解决方案.它试图编写系统偏好.如果失败,则用户可能不是管理员.
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Cod*_*nci 20
我发现这个代码片段在线,我认为会为你完成这项工作.
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;
}
Run Code Online (Sandbox Code Playgroud)
它仅适用于Windows,并内置于核心Java包中.我刚刚测试了这段代码,它确实有效.它让我感到惊讶,但确实如此.
SID S-1-5-32-544是Windows操作系统中Administrator组的ID.
| 归档时间: |
|
| 查看次数: |
10828 次 |
| 最近记录: |