我正在用 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()
表明该过程实际上是活跃的;但是,我没有看到新进程的任何证据,并且 Windows 也没有提示我授予权限。
我不熟悉使用exec()
在Java中,所以很可能我以某种方式误解了它的用法。就此而言,我在这里尝试做的事情可能吗?如果没有,是否有一个简单的替代方案可以真正让我得到我正在寻找的结果?
好吧,我终于找到了一个令我满意的解决方案;这有点难看,但它适合我正在做的事情。
我借用了代码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
}
The checkPrivileges
方法与上面相同,并且Elevator
类实际上与链接解决方案中出现的类完全相同(我只是取出了不需要的main
方法)。该方案假设要提升的进程是一个jar;改变它以满足您的个人需求应该不会太困难。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)