加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

在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方法).该解决方案假设要升高的过程是一个罐子;改变这一点以满足您的个人需求应该不会太难.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读