tags:

views:

247

answers:

4

Hello.

Is it any cross-platform way to check that my python script is executed under admin rights? Unfortunately, os.getuid() is UNIX-only and is not available under windows :(.

+4  A: 

Try doing whatever you need admin rights for, and check for failure.

This will only work for some things though, what are you trying to do?

cobbal
I need to install a system-wide font, this require admin rights on windows vista+.
Eye of Hell
+2  A: 

It's better if you check which platform your script is running (using sys.platform) and do a test based on that, e.g. import some hasAdminRights function from another, platform-specific module.

On Windows you could check whether Windows\System32 is writable using os.access, but remember to try to retrieve system's actual "Windows" folder path, probably using pywin32. Don't hardcode one.

macbirdie
I'm very curious right about an hasAdminRights() function of some platform-specific module :). Unfortunately, google can't answer such function's name. Testing system32 look reasonable, but the code will look like a crude hack :(.
Eye of Hell
Sorry, it was just an example of a function name. I don't think there's a better way to do it than to check for platform type. The most right method would be to try to elevate your rights with UAC the moment you want to install the font, because you don't need those all the time. So first you would have to check if you have admin rights on pre-Vista and fail at start. If it's post XP/2003, fail only if you can't elevate the rights, since e.g. user didn't want give permission to UAC or doesn't have administrator's password.
macbirdie
+5  A: 
import ctypes, os
try:
 is_admin = os.getuid() == 0
except AttributeError:
 is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0

print is_admin
Eye of Hell
use except AttributeError, it's a bad practice to except everything
SilentGhost
Done, thanks! <15 chars>
Eye of Hell
IsUserAnAdmin() returns an integer value, so you'll need to add a != 0 test at the end of that line to get a boolean result.
dave-ilsw
Thanks, added <15 chars>
Eye of Hell
+1  A: 

Administrator group membership (Domain/Local/Enterprise) is one thing..

tailoring your application to not use blanket privilege and setting fine grained rights is a better option especially if the app is being used iinteractively.

testing for particular named privileges (se_shutdown se_restore etc), file rights is abetter bet and easier to diagnose.

Bob Blanchett
If script runs external apps / scripts that is documented like "use sudo" it's kind of hard to guess what rights they exactly need.
Eye of Hell