在Windows上以管理员身份运行Java应用程序
发布时间:2020-12-14 02:46:48 所属栏目:Windows 来源:网络整理
导读:我正在用 Java编写安装程序,因此需要提升权限才能访问Program Files目录.根据我在网上找到的信息,我编写了如下实现: public static void main(String args[]) { if (!checkPrivileges()) { // spawn a copy w/ elevated privileges Runtime runtime = Runti
我正在用
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也没有提示我授予权限. 我不熟悉在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") + "binjava","-jar " + """ + decodedPath + """); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { // Run with elevated privileges } checkPrivileges方法从上面保持不变,Elevator类几乎与链接解决方案中出现的相同(我刚刚取出了不需要的main方法).该解决方案假设要升高的过程是一个罐子;改变这一点以满足您的个人需求应该不会太难. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- windows-server-2008-r2 – 将Win 2008 R2域 – Win 2016迁
- 以编程方式在Server Manager中添加Windows 2008 Server R2中
- windows – 从文件夹和子文件夹中复制前10个文件
- Windows上Jenkins的git插件不使用带子模块的凭据
- windows-phone-8 – 添加辅助Windows Phone 8磁贴
- Anaconda 安装 TensorFlow ImportError:DLL加载失败,错误
- windows – 在matlab中监视内存
- windows-server-2012 – 如何更改指定的AD控制器?
- 部署Windows Mobile 6 Professional模拟器应用程序
- libusb_open在Windows 7上返回’LIBUSB_ERROR_NOT_SUPPORTE