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

有没有办法来检查是否有任何用户在pipe理员组?

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

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

但是,如果我以userAlogin,我想知道userZed是否具有pipe理员权限。

任何指针或build议将有所帮助,似乎我无法追查ctypes.windll.shell32上的任何文档。

这里是一个网站的代码来做到这一点:

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

我测试了它,它工作。 可以如下使用,注意字符串必须是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) 
 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”应该是“管理员”