views:

473

answers:

3

Hello, how can i check admin-privileges for my script during running?

+5  A: 

On Unix you can check whether you are root using the os.getuid function:

os.getuid() == 0 and "root" or "not root"
Stephan202
+5  A: 

The concept of "admin-privileges" in our day of fine grained privilege control is becoming hard to define. If you are running on unix with "traditional" access control model, getting the effective user id (available in os module) and checking that against root (0) could be what you are looking for. If you know accessing a file on the system requires the privileges you want your script to have, you can use the os.access() to check if you are privileged enough.

Unfortunately there is no easy nor portable method to give. You need to find out or define the security model used, what system provided APIs are available to query and set privileges and try to locate (or possibly implement yourself) the appropriate python modules that can be used to access the API.

The classic question, why do you need to find out? What if your script tries to do what it needs to do and "just" catches and properly handles failures?

Marko Teiste
+1. All valid considerations. Indeed sometimes it's better to just go ahead and act on failures.
Stephan202
+1  A: 

If you're just trying to see if you have access to a certain file that requires administrative rights, a good way to check would be:

import os
print os.access("/path/to/file", os.W_OK) 
#replace W_OK with R_OK to test for read permissions

On the other hand, if you really need to know if a user is an administrative account, you can also use this code on Windows 2000 and higher:

import ctypes
print ctypes.windll.shell32.IsUserAnAdmin()

Therefore, a better, cross-platform way to find out if an user is an administrator is:

import ctypes, os
try:
 is_admin = os.getuid() == 0
except:
 is_admin = ctypes.windll.shell32.IsUserAnAdmin()

print is_admin

Of course, this method will only detect if the user is root on Unix, or is a member of the Administrators group on Windows. However, this is sufficient for most purposes, in my opinion.

Also note that this will fail on Windows versions below 2000, as well as Windows ME, since those are DOS-based versions of Windows and don't have any notion of permissions.

Zoip