首页 > 编程语言 > 详细

python :通过Ldap 3 模块查询AD 组和 AD 用户名单

时间:2019-07-17 22:48:34      阅读:451      评论:0      收藏:0      [点我收藏+]
from ldap3 import Server, Connection, ALL, NTLM

定义一个类用于操作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

python :通过Ldap 3 模块查询AD 组和 AD 用户名单

原文:https://blog.51cto.com/unicom/2421224

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!