具有root权限的GLib运行命令

时间:2020-06-13 00:43:06

标签: javascript gnome-shell-extensions

我正在编写一个非常简单的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)连接在一起。

1 个答案:

答案 0 :(得分:1)

首先,避免在扩展名中使用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);
    }
}   
相关问题