简体   繁体   English

如何在Mac OS X中从Python以root身份运行命令?

[英]How to run command as root from Python in Mac OS X?

In my Python GUI application, I have to run a command as root to perform a certain action (to be specific, it installs a Python module system-wide). 在我的Python GUI应用程序中,我必须以root用户身份运行命令以执行某些操作(具体来说,它会在系统范围内安装Python模块)。 On Linux I simply use gksudo or kdesu prefixed to the command passed to subprocess.Popen(). 在Linux上,我只需在传递给subprocess.Popen()的命令前使用gksudo或kdesu即可。 There doesn't seem to be a Mac equivalent, unfortunately. 不幸的是,似乎没有与Mac相当的产品。 I have seen this question before pointing to some complicated Objective-C code called BetterAuthorizationSample... I don't really understand it and would prefer to not write Objective-C code to do this simple task. 在指向一些称为BetterAuthorizationSample的复杂Objective-C代码之前,我已经看到了这个问题。我不太了解它,宁愿不编写Objective-C代码来完成此简单任务。 If there's a simpler way, I'd like to know. 如果有更简单的方法,我想知道。 I'm thinking I could make my own password dialog box and pass it to regular command-line sudo on stdin. 我想我可以创建自己的密码对话框,并将其传递给stdin上的常规命令行sudo。

I don't know off the top of my head how to elevate your privileges, but you could use a bit of AppleScript to ask for a password. 我不知道如何提高权限,但是您可以使用一些AppleScript要求输入密码。 For an example, see https://github.com/apenwarr/sshuttle/blob/master/ui-macos/askpass.py 有关示例,请参见https://github.com/apenwarr/sshuttle/blob/master/ui-macos/askpass.py

I have not found an optimal solution, but I just posted my currently working solution here 我没有找到最佳的解决方案,但我只是在这里发布了我目前正在使用的解决方案

It uses osascript to relaunch itself with root permissions. 它使用osascript以root权限重新启动自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM