在某些时候,我的应用程序需要执行管理任务,例如在 /etc 中创建文件或使用 root 权限运行命令。
我知道可以做一个问答:
os.popen("pkexec foo bar")
Run Code Online (Sandbox Code Playgroud)
但我也知道这不是可预见的干净方式。对用户来说有些烦人,因为他总是需要重新输入密码,而不是进行类似会话的处理。
我非常乐观,因为我找到了用于身份验证的 python 示例。
这是一个立即生效的简单示例:
import dbus
bus = dbus.SystemBus()
proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()
subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.policykit.exec'
details = {}
flags = 1 # AllowUserInteraction flag
cancellation_id = '' # No cancellation id
result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
print result
Run Code Online (Sandbox Code Playgroud)
我一直很天真地认为在授权后我可以继续使用一些 os.popen() 命令在脚本中。现在我知道了 :(
我可以在上面的示例中看到元组结果,但是在进一步的文档中,我找不到此时可以继续执行的工作代码。
这个结果与我有什么关系?我怎样才能继续执行我需要的任务?是否有提供可用方法的示例的 python 参考?
我尝试使用 dir() 列出授权方法,但找不到任何线索如何继续。
我真的想避免使用我的后备,但这将是我的最后手段。请帮助我以正确的方式做这件事:)
感谢致敬
安德烈 …