在脚本中使用 sudo 时如何通过 GUI 提示询问密码?

Pan*_*dya 19 password prompt gui sudo shell-script

我将 Trisquel GNU/Linux 与 GNOME Flashback 桌面环境一起使用。我需要一个 GUI 密码提示,供用户sudo在脚本中执行命令。示例考虑以下脚本:

zenity --question --text="Do you want to install this package?"
if [[ $? -eq 0 ]]; then sudo apt-get install package
else zenity --warning
fi
Run Code Online (Sandbox Code Playgroud)

将按照以下方式执行(运行),即不在终端内:

截屏

因此,需要询问密码才能运行命令,sudo否则无法执行任务。

因此,如何通过 GUI 提示询问密码?

Pan*_*dya 31

您可以在-A, --askpass选项的帮助下通过 GUI 提示询问密码sudo

sudo联机帮助页:

-A, --askpass
                 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 sudo.conf(5) 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.
Run Code Online (Sandbox Code Playgroud)

所以,你可以图形化的辅助程序,如ssh-askpass会提示输入密码短语用户使用GNOME:

$ which ssh-askpass
/usr/bin/ssh-askpass
Run Code Online (Sandbox Code Playgroud)

因此,将以下行添加到/etc/sudo.conf

# Path to askpass helper program
Path askpass /usr/bin/ssh-askpass
Run Code Online (Sandbox Code Playgroud)

你会发现 GUI 密码提示:

屏幕截图1

您也可以使用其他类似zenity的程序。我使用以下示例:

$ cat /etc/sudo.conf
# Path to askpass helper program
Path askpass /usr/local/bin/zenity_passphrase
Run Code Online (Sandbox Code Playgroud)

直接用作命令zenity_passphrase的自定义脚本在哪里:

$ cat $(which zenity_passphrase)
#!/bin/bash
zenity --password --title="sudo password prompt" --timeout=10
Run Code Online (Sandbox Code Playgroud)

其工作原理如下:

屏幕截图2


笔记:

  • 您还可以使用gksudo(用于 su 和 sudo 的 GTK+ 前端)而不是sudo在带有 GUI 提示的脚本中使用(gksu并且gksudo已过时并在 2019-2020 年废弃):

    屏幕截图3

  • 您还可以将pkexecpolkit应用程序)与一些(对于其他需要配置的)应用程序/命令一起使用:

    截屏