Cross-platform way to check admin rights in a Pyth

2019-03-15 03:13发布

Is there any cross-platform way to check that my Python script is executed with admin rights? Unfortunately, os.getuid() is UNIX-only and is not available under Windows.

5条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-15 03:22

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.

查看更多
家丑人穷心不美
3楼-- · 2019-03-15 03:24
import ctypes, os
try:
 is_admin = os.getuid() == 0
except AttributeError:
 is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0

print is_admin
查看更多
放我归山
4楼-- · 2019-03-15 03:31

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?

查看更多
趁早两清
5楼-- · 2019-03-15 03:31

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.

查看更多
forever°为你锁心
6楼-- · 2019-03-15 03:40

Here's a utility function I created from the accepted answer:

import os
import ctypes

class AdminStateUnknownError(Exception):
    """Cannot determine whether the user is an admin."""
    pass


def is_user_admin():
    # type: () -> bool
    """Return True if user has admin privileges.

    Raises:
        AdminStateUnknownError if user privileges cannot be determined.
    """
    try:
        return os.getuid() == 0
    except AttributeError:
        pass
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() == 1
    except AttributeError:
        raise AdminStateUnknownError
查看更多
登录 后发表回答