gpt4 book ai didi

java - 在 Windows 上以管理员身份运行 Java 应用程序

转载 作者:可可西里 更新时间:2023-11-01 13:46:46 24 4
gpt4 key购买 nike

我正在用 Java 编写安装程序,因此需要提升权限才能访问 Program Files 目录。根据网上查到的资料,我写了一个实现如下:

public static void main(String args[]) {
if (!checkPrivileges()) { // spawn a copy w/ elevated privileges
Runtime runtime = Runtime.getRuntime();
try {
Process p = runtime.exec(
"runas /profile /user:Administrator \"java -cp . main.Main\"");
} catch (IOException e) { ... }
} else {
// Run with elevated privileges
}
}

我用来检查权限的测试根据找到的答案稍作修改 here看起来像这样:

private static boolean checkPrivileges() {
File testPriv = new File("C:\\Program Files\\");
if (!testPriv.canWrite()) return false;
File fileTest = null;
try {
fileTest = File.createTempFile("test", ".dll", testPriv);
} catch (IOException e) {
return false;
} finally {
if (fileTest != null)
fileTest.delete();
}
return true;
}

当我运行它时,它没有通过特权测试——如预期的那样——并调用了 exec。通过查看 p.isAlive() 检查调用是否正常显示该进程实际上是 Activity 的;但是,我没有看到新进程的任何证据,Windows 也没有提示我授予权限。

我不熟悉在 Java 中使用 exec(),所以我很可能以某种方式误解了它的用法。就此而言,我在这里尝试做的事情是否可行?如果没有,是否有一种直接的替代方法可以真正让我获得我正在寻找的结果?

最佳答案

好吧,我终于找到了一个我满意的解决方案;它有点丑陋,但它适用于我正在做的事情。

我从this借用了代码回答做实际的特权提升;从那里开始,问题之一是实际让该解决方案与 Java 一起工作。最终的代码如下所示:

    if (!checkPrivileges()) {
try {
String jarPath = DownloaderMain.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(jarPath, "UTF-8");
decodedPath = decodedPath.substring(1, decodedPath.length());
Elevator.executeAsAdministrator(System.getProperty("java.home") + "\\bin\\java", "-jar " + "\"" + decodedPath + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// Run with elevated privileges
}

checkPrivileges 方法与上面没有变化,Elevator 类实际上与链接解决方案中出现的类相同(我只是去掉了不需要的 main 方法)。该解决方案假设要提升的进程是一个 jar;改变这一点以满足您的个人需求应该不会太困难。

关于java - 在 Windows 上以管理员身份运行 Java 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26664176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com