我可以在python脚本或.desktop文件中使用pkexec吗?

从以下问题

  • 为什么默认不再安装gksu?
  • 何时使用pkexec与gksu / gksudo?

我们发现gksu从长远来看将不再受支持,默认情况下不会安装> = 13.04。 相反,我们应该使用pkexec,它可以很好地用于非图形应用程序,但不能用于GUI上的应用程序:

pkexec gedit 

在.desktop文件中替换gksu时

 EXEC=pkexec /usr/bin/gedit 

或者当我运行python脚本来运行具有root权限的图形应用程序时,我收到以下错误:

 >>>subprocess.Popen(['pkexec','gedit']) ** (gedit:3203): WARNING **: Could not open X display 

如果我不应该依赖gksu,我将如何重新编写我的脚本或我的.desktop文件以支持身份validation对话框并以root身份运行应用程序?

首先在/usr/share/polkit-1/actions/创建一个.policy操作文件。 以“供应商分层”方式命名操作文件是常规的,例如com.ubuntu.pkexec.gparted.policyorg.debian.apt.policy

然后粘贴以下内容:

     Run [Full Program Name] Authentication is required to run [Full Program Name]  no no auth_admin_keep  [Full Program Path] TRUE   

用适当的值替换[Short/Full Program Name/Path] ,例如geditgedit Text Editor/usr/bin/gedit值不需要与所选文件名匹配(并且单个文件可以包含多个操作),但通常filename是其所有操作的前缀。

保存文件后,特定程序将使用X和GUI等运行。

另一个修复似乎是:在/etc/pam.d/polkit-1中添加以下行:

session可选pam_xauth.so

用户脚本的另一个修复:确定脚本中的相应环境变量。

您可以使用如下所示的代码段来执行此操作:

 getXuser() { user=`pinky -fw | awk '{ if ($2 == ":'$displaynum'" || $(NF) == ":'$displaynum'" ) { print $1; exit; } }'` if [ x"$user" = x"" ]; then startx=`pgrep -n startx` if [ x"$startx" != x"" ]; then user=`ps -o user --no-headers $startx` fi fi if [ x"$user" = x"" ]; then user=$(pinky -fw | awk '{ print $1; exit; }') fi if [ x"$user" != x"" ]; then userhome=`getent passwd $user | cut -d: -f6` export XAUTHORITY=$userhome/.Xauthority else export XAUTHORITY="" fi export XUSER=$user } for x in /tmp/.X11-unix/*; do displaynum=`echo $x | sed s#/tmp/.X11-unix/X##` getXuser; if [ x"$XAUTHORITY" != x"" ]; then export DISPLAY=":$displaynum" fi done 

(基于ACPI getXuser函数)

如果您发现.desktop文件仍无法正常工作,您可以尝试将pkexec commandline包装在sh片段中,例如:

 Exec=sh -c "pkexec --user root script_that_needs_root.sh" 

最后一个问题是一个已知的错误,显然:

http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=690339

https://bugzilla.xfce.org/show_bug.cgi?id=9373

http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=650038

https://bugzilla.gnome.org/show_bug.cgi?id=686059