Friday, July 18, 2008

Running Python Scripts with Administrator Privileges on MAC OS X


I had a piece of software written in Python. I come primarily from Windows background where permissions etc. are quite hazy. 

On MAC OS X I wanted this software to be able to run with Administrator privileges. Apple has an Authentication API which enables an application to request for administrator privileges from the user whenever it needs it. Unfortunately I couldn't find out any way to access the authentication API directly from Python code.


AppleScript (MAC's built-in scripting language) has a very simple and straightfoward way to execute any script with admin privileges. 

Lets look at a simple example first:
do shell script ¬
"echo 'abc' > /Applications/MyTestFile" with administrator privileges

You can open Script Editor from /Applications/AppleScript/Script and write the above example.

Interesting thing to note here is:
  • I am trying to do something which will not succeed with administrator privileges
  • The "with administrator privileges" clause ensures that AppleScript will ask you to grant administrator privileges to the shell script before execution
  • If you don't grant administrator privileges (may be you don't know or you forgot the password, or may be you don't want the shell script to run), the script will not be run.
  • If you grant the privileges, it will do as programmed above; i.e. write 'abc' to a file in /Applications.

Administrator privileges for Python programs

It must be easy for you to guess how to request for administrator privileges for running a Python program. Let me just put the code for clarity:
do shell script ¬
"/usr/bin/python" with administrator privileges

  • The solution requires you to request for privileges even before the python program started running. Thus if you wanted something where you could request the privileges only on need basis, this solution won't work. But at least something is better than nothing.

No comments: