【问题标题】:make javafx jar prompt for Admin credentials with GUI while using sudo command使用 sudo 命令时使用 GUI 使 javafx jar 提示管理员凭据
【发布时间】:2025-11-30 06:35:01
【问题描述】:

我正在尝试编写一个 javafx 应用程序,它将在 mac 设备中安装另一个 pkg。我已经使用了命令

sudo -v installer -pkg /Downloads/one.pkg -target /

从 javafx 应用程序单击按钮安装 pkg。

public class macinstall extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Sample");
        Button button = new Button("Click");

        EventHandler<ActionEvent> event = ae -> install2();
        button.setOnAction(event);

        HBox hbox = new HBox(button);

        Scene scene = new Scene(hbox, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void runProcess(String[] Command) {
        ProcessBuilder builderObj = new ProcessBuilder(Command);
        try {
            Process process = builderObj.start();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void install2() {
        String[] installCommand = {"bash", "-c", "sudo -v installer -pkg /Downloads/one.pkg -target /"};
        runProcess(installCommand);
        System.out.println("Install Completed");
    }
}

当我通过终端运行该程序时,该程序有效,在终端中询问管理员密码。 但是当我使用 jre 作为 javafx 应用程序运行时。它不要求管理员凭据。

【问题讨论】:

  • 那么实际发生了什么?我希望这只是挂起......
  • 是的,它只是挂起。点击按钮后。有没有办法让 gui 弹出窗口在处理安装之前询问管理员凭据?
  • 我认为您需要 1. 在启动进程之前提示用户输入密码,2. 使用-S 选项到sudo,以及 3. 将密码发送到process's standard input
  • 您可能还应该在后台线程中运行该进程。

标签: java macos javafx terminal jar


【解决方案1】:

感谢您的建议 James_D。

String[] installCommand = {"osascript","-e","do shell script "installer -pkg /Downloads/one.pkg -target /" 具有管理员权限"};

我使用了上面的命令,它从 OSX 访问了 GUI,在安装 pkg 之前给了我用户身份验证的弹出窗口。

现在用户身份验证如下图所示。

但我想知道,是否有可能更改图像中弹出的身份验证消息。 就像而不是“osascript 想要进行更改。输入您的密码以允许这样做”。是否可以配置我的首选字符串或在那里提及我的应用程序名称?

【讨论】:

  • 如果您有(其他)问题,请发布 .. question :) - 答案部分专门用于回答
  • 好的,@kleopatra。