检查任意用户是否在使用Python的管理员组中

时间:2013-04-02 20:36:08

标签: python windows python-2.7 admin ctypes

有没有办法检查任何给定用户是否在管理员组中?

我知道如何检查当前用户是否是管理员使用:

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

但是,如果我以userA身份登录,我想知道userZed是否具有管理员权限。

任何指针或建议都会有所帮助,似乎我无法追踪ctypes.windll.shell32上的任何文档。

2 个答案:

答案 0 :(得分:3)

这是一个包含以下代码的网站:

http://skippylovesmalorie.wordpress.com/tag/python-windows/

我测试了它并且它有效。可以按如下方式使用,请注意字符串 HAVE 为unicode或登录失败:

Python 2.7:

print(user_is_admin(u"johndoe", u"password123", u"MYDOMAIN"))

Python 3.x:

print(user_is_admin("johndoe", "password123", "MYDOMAIN"))

以下是代码,供将来参考:

import ctypes
import ctypes.wintypes

def current_user_is_admin():
    return user_token_is_admin(0)

def user_is_admin(username, password, domain=None):
    """note that username, password, and domain should all be unicode"""

    LOGON32_LOGON_NETWORK = 3
    LOGON32_PROVIDER_DEFAULT = 0
    token = ctypes.wintypes.HANDLE()
    if ctypes.windll.advapi32.LogonUserW(username, domain, password,
            LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ctypes.byref(token)) == 0:
        raise Exception("user logon failed")

    try:
        return user_token_is_admin(token)
    finally:
        ctypes.windll.kernel32.CloseHandle(token)


def user_token_is_admin(user_token):
    """
    using the win32 api, determine if the user with token user_token has administrator rights
    """
    class SID_IDENTIFIER_AUTHORITY(ctypes.Structure):
        _fields_ = [
            ("byte0", ctypes.c_byte),
            ("byte1", ctypes.c_byte),
            ("byte2", ctypes.c_byte),
            ("byte3", ctypes.c_byte),
            ("byte4", ctypes.c_byte),
            ("byte5", ctypes.c_byte),
        ]
    nt_authority = SID_IDENTIFIER_AUTHORITY()
    nt_authority.byte5 = 5

    SECURITY_BUILTIN_DOMAIN_RID = 0x20
    DOMAIN_ALIAS_RID_ADMINS = 0x220
    administrators_group = ctypes.c_void_p()
    if ctypes.windll.advapi32.AllocateAndInitializeSid(ctypes.byref(nt_authority), 2,
        SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS,
        0, 0, 0, 0, 0, 0, ctypes.byref(administrators_group)) == 0:
        raise Exception("AllocateAndInitializeSid failed")

    try:
        is_admin = ctypes.wintypes.BOOL()
        if ctypes.windll.advapi32.CheckTokenMembership(
                user_token, administrators_group, ctypes.byref(is_admin)) == 0:
            raise Exception("CheckTokenMembership failed")
        return is_admin.value != 0

    finally:
        ctypes.windll.advapi32.FreeSid(administrators_group)

答案 1 :(得分:0)

import win32net


def if_user_in_group(group, member):
    members = win32net.NetLocalGroupGetMembers(None, group, 1)
    return member.lower() in list(map(lambda d: d['name'].lower(), members[0])) 


# Function usage
print(if_user_in_group('SOME_GROUP', 'SOME_USER'))

当然,在你的情况下,'SOME_GROUP'应该是'管理员'