如何以编程方式使用 sudo? IE。将 sudo 集成到我的 GUI 中

问题描述 投票:0回答:2

我正在编写一个程序,第一次运行时暂时需要 root 来执行配置更改(在

/etc
中创建一个文件)。

如何通过在图形对话框中询问用户密码来临时获得 root 权限?

该程序使用 Qt,如果它只能在 Ubuntu 上运行,我会相当高兴,但我不想假设他们已经安装了

gksudo
或其他任何东西。我也无法使用
SUID

我唯一能想到的就是提供我自己的密码对话框,并通过

sudo
(或其不太不安全的表兄弟之一)将其提供给命令行
system()
二进制文件。

这看起来很老套——命令行前端通常是一个可怕的想法,应该不惜一切代价避免。那么有没有更好的办法呢?也许有一个 libsudo,或者某种使用 IPC 的方法?

注意:这不是重复的。或者至少,那里的答案不会将其视为我要问的问题。

root sudo
2个回答
2
投票

来自

man sudo

   -A          Normally, if sudo requires a password, it will read it from the
               user's terminal.  If the -A (askpass) option is specified, a
               (possibly graphical) helper program is executed to read the user's
               password and output the password to the standard output.  If the
               SUDO_ASKPASS environment variable is set, it specifies the path to
               the helper program.  Otherwise, if /etc/sudo.conf contains a line
               specifying the askpass program, that value will be used.  For
               example:

                   # Path to askpass helper program
                   Path askpass /usr/X11R6/bin/ssh-askpass

               If no askpass program is available, sudo will exit with an error.

您可以使用许多系统上安装的 ssh-askpass,或者编写自己的密码提示命令,然后将其提供给 sudo。这仍然有点棘手,但是您不必太担心将密码传达给 sudo。


0
投票

这是使用 ProcessBuilder 在 mac 机器上为我工作的唯一解决方案:

try {
        String command = "sudo -S ls -l /";

        ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", command);

        // Redirect error stream to output stream
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();

        // Create a BufferedWriter to write the sudo password
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
        writer.write("your_sudo_password\n");
        writer.flush();

        // Read the process output
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        // Wait for the process to finish
        int exitCode = process.waitFor();
        System.out.println("Process exited with code " + exitCode);

    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
© www.soinside.com 2019 - 2024. All rights reserved.