定义一个类用于操作AD
class Operate_AD():
def init(self,Domain,User,Password):
self.domain=Domain
self.user=User
self.pwd=Password
self.DC=‘,‘.join([‘DC=‘ + dc for dc in Domain.split(‘.‘)])
self.pre = Domain.split(‘.‘)[0].upper()
self.server = Server(self.domain, use_ssl=True,get_info=ALL)
self.conn = Connection(self.server, user=self.pre+‘\‘+self.user, password=self.pwd, auto_bind=True)
def Get_All_UserInfo(self):
‘‘‘
查询组织下的用户
org: 组织,格式为:aaa.bbb 即bbb组织下的aaa组织,不包含域地址
‘‘‘
att_list = [‘displayName‘, ‘userPrincipalName‘,‘userAccountControl‘,‘sAMAccountName‘,‘pwdLastSet‘]
# org_base = ‘,‘.join([‘OU=‘ + ou for ou in org.split(‘.‘)]) + ‘,‘ + self.DC
res = self.conn.search(search_base=self.DC,search_filter=‘((objectclass=person))‘,attributes=att_list, paged_size=100,search_scope=‘SUBTREE‘)
if res:
for users in self.conn.entries:
yield users
else:
print(‘查询失败: ‘, self.conn.result[‘description‘])
return None
def Get_All_GroupInfo(self):
‘‘‘
查询组织下的用户
org: 组织,格式为:aaa.bbb 即bbb组织下的aaa组织,不包含域地址
‘‘‘
att_list = [‘cn‘,‘member‘,‘objectClass‘,‘userAccountControl‘,‘sAMAccountName‘,‘description‘]
# org_base = ‘,‘.join([‘OU=‘ + ou for ou in org.split(‘.‘)]) + ‘,‘ + self.DC
res = self.conn.search(search_base=self.DC,search_filter=‘(objectclass=group)‘,attributes=att_list, paged_size=10,search_scope=‘SUBTREE‘)
if res:
for group in self.conn.entries:
yield group
else:
print(‘查询失败: ‘, self.conn.result[‘description‘])
return None
if __name__ == ‘__main__‘:
act=Operate_AD(‘demo.com‘,‘testaccount‘,‘testpassword‘)
for user in act.Get_All_UserInfo():
print(user)
# for group in act.Get_All_GroupInfo():
# print(group)
备注: 微软search_filter 语法
https://docs.microsoft.com/en-us/windows/win32/adsi/search-filter-syntax
原文:https://blog.51cto.com/unicom/2421224