在 Windows 下检查 Python 脚本中的管理员权限的跨平台方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1026431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:17:57  来源:igfitidea点击:

Cross-platform way to check admin rights in a Python script under Windows?

pythonprivilegesadmin-rights

提问by grigoryvp

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.

是否有任何跨平台的方法来检查我的 Python 脚本是否以管理员权限执行?不幸的是,os.getuid()仅适用于 UNIX,并且在 Windows 下不可用。

回答by grigoryvp

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

print is_admin

回答by cobbal

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?

不过,这只适用于某些事情,你想做什么?

回答by macbirdie

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.

如果您检查脚本正在运行的平台(使用sys.platform)并基于此进行测试,则更好,例如从另一个特定于平台的模块导入一些 hasAdminRights 函数。

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

在 Windows 上,您可以Windows\System32使用来检查是否可写os.access,但请记住尝试检索系统的实际“Windows”文件夹路径,可能使用 pywin32。不要硬编码一个。

回答by Bryce Guinta

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

回答by Bob Blanchett

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.

测试特定的命名权限(se_shutdown se_restore 等),文件权限更好,更容易诊断。