具有 root 权限的 GLib 运行 命令

GLib run command with root privileges

我正在编写一个非常简单的 gnome 扩展供个人使用(在 javascript 中)。

我使用 运行 控制台命令 GLib.spawn_command_line_sync("command");

GNOME Shell 版本 3.36.2

我需要什么

我只需要 运行 一个命令但具有 root 权限,我怎样才能使 GLib.spawn_command_line_sync("sudo command"); 之类的东西起作用?

我想使用默认的 Authentication Required gnome 对话框输入密码。

我知道什么

我阅读了很多源代码并找到了对话框的定义,但我不明白如何使用它,因为找不到一个使用示例。

我不知道如何将这两者联系起来(对话框和 GLib)。

首先,避免在扩展中使用GLib.spawn_command_line_sync()。此函数将在与动画和用户交互相同的线程中同步执行,阻塞直到完成。

如果您不需要从命令输出或退出状态,请使用GLib.spawn_command_line_async()。如果确实需要输出或退出状态,请使用 Gio.Subprocesscommunicate_utf8_async()

要以用户身份执行特权命令,最简单的方法可能是使用 pkexec,它将使用您想要的对话框(您可以在终端中测试此 运行):

// With GLib (no output or success notification)
let cmd = 'apt-get update';

try {
    GLib.spawn_command_line_async('pkexec ' + cmd);
} catch (e) {
    logError(e);
}

// With GSubprocess (output and success notification)
let args = ['apt-get', 'update'];

function privelegedExec(args) {
    try {
        let proc = Gio.Subprocess.new(
            ['pkexec'].concat(args),
            Gio.SubprocessFlags.STDOUT_PIPE | Gio.SubprocessFlags.STDERR_PIPE
        );

        proc.communicate_utf8_async(null, null, (proc, res) => {
            try {
                let [, stdout, stderr] = proc.communicate_utf8_finish(res);

                // Failure
                if (!proc.get_successful())
                    throw new Error(stderr);

                // Success
                log(stdout);
            } catch (e) {
                logError(e);
            }
        });
    } catch (e) {
        logError(e);
    }
}