通过 osascript 在 MAC OSX 上将您的 java 应用提升为管理员权限

Elevate your java app as Admin privilege on MAC OSX by osascript

我需要你的帮助才能知道我的错误在哪里:)

public class Main extends JFrame{
    public Main() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                setVisible(true);
            }
        });
    }

    public static void main(String[] args) throws IOException, URISyntaxException {
        new Main();
        File executor = File.createTempFile("Executor", ".sh");
        PrintWriter writer = new PrintWriter(executor, "UTF-8");

        writer.println("#!/bin/bash");
        writer.println();
        writer.println("java -$* > /tmp/output.txt 2>&1 &"); // ***
        writer.close();
        executor.setExecutable(true); // ***

        File elevator = File.createTempFile("Elevator", ".sh");
        writer = new PrintWriter(elevator, "UTF-8");
        writer.println("#!/bin/bash");
        writer.println();
        writer.println(String.format("osascript -e \"do shell script \\"%s $*\\" with administrator privileges\"",
                executor.getPath()));
        writer.close();
        elevator.setExecutable(true); // ***

        Runtime.getRuntime().exec(String.format("%s -cp %s Main param", // ***
                elevator.getPath(),
                Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()));
    }
}

此代码假设以管理员权限重新运行应用程序。 要求输入管理员密码,但此后应用程序无法运行。 为什么 ?我的输出没有错误

谢谢

我知道我的问题出在哪里了! 这一行:

writer.println("java -$* > /tmp/output.txt 2>&1 &");`

必须删除 - 在 $*

之前
writer.println("java $* > /tmp/output.txt 2>&1 &");

有效!对于像我一样搜索如何在 MAC OS X 上为您的 JAVA 应用程序启用管理员权限的每个人,您现在有了代码 !

此代码完美运行!

        File executor = File.createTempFile("Executor", ".sh");
        PrintWriter writer = new PrintWriter(executor, "UTF-8");

        writer.println("#!/bin/bash");
        writer.println();
        writer.println("java $* > /tmp/output.txt 2>&1 &");
        writer.close();
        executor.setExecutable(true); 

        File elevator = File.createTempFile("Elevator", ".sh");
        writer = new PrintWriter(elevator, "UTF-8");
        writer.println("#!/bin/bash");
        writer.println();
        writer.println(String.format("osascript -e \"do shell script \\"%s $*\\" with administrator privileges\"",
                executor.getPath()));
        writer.close();
        elevator.setExecutable(true);

        Runtime.getRuntime().exec(String.format("%s -cp %s Main param", 
                elevator.getPath(),
                Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()));

尽情享受吧!