Python使用ldap3操作微软AD

对于client连接ldap server的策略,ldap3提供了4种选择,可以通过client_strategy设置Connection object应用哪种策略:

l  SYNC

l  ASYNC

l  RESTARTABLE

l  REUSABLE

同步策略(SYNC, RESTARTABLE),所有的ldap操作返回True/False

异步策略(ASYNC, REUSABLE)返回一个msgid(一个数值),异步策略发送请求后不用等待响应,需要响应的时候直接使用get_response(message_id)获取结果。等待响应的超时时间可以通过get_responsetimeout参数指定,默认10s。如果使用get_request=True in the get_response(),同时会返回发送的请求字典。

 

建立连接:

blob.png

blob.png


blob.png

blob.png


建立Server对象时使用get_info=ldap3.ALL参数,建立Connection连接之后可以获取到server信息(匿名获取),从中可以获取到域名信息,域控计算机名,ldap server支持的ExtensionControl

blob.png

 

ldap serverSchema数据库中存储了ldap server中的对象的已知类型信息,可以通过server.schema获取到(微软AD需要鉴权,匿名用户无法获取),里面存储了ldap server理解那些数据类型,同时也指定,哪些属性被ldap server中的对象支持

blob.png

使用鉴权用户连接ldap server后可以查看server.shema等高级别操作。查看当前鉴权用户信息。以下连接使用的不安全的连接,密码信息明文传输,可以被抓取。使用authentication=ldap3.NTLM的鉴权方式无法显示的看到鉴权信息。

blob.png

blob.png

blob.png

可以使用以下方式建立安全连接,2种方式都是建立TLS连接:

l  LDAP over TLS

l  the StartTLS extended operation     ##微软AD不支持

 

ldap查询

ldap查询基于search_basesearch_filterfilter是个表达式:

l  查询所有显示名叫John并且email以‘@example.org’结尾的用户:(&(givenName=John)(mail=*@example.org))

l  查询显示名为Jhon或者Fred并且邮箱以@example.org结尾的用户

(&

(|

(GivenName=Jhon)

(givenName=Fred)

)

( mail=*@example.org)

)

搜索search_base下的所有用户,默认search_scope='SUBTREE',没有指定请求任何attribute,只返回entriesdistinguished Name,请求成功(同步strategy)返回True,conn.entries获取查询到的结果:

conn.search(base_search,'(objectclass=person)')

conn.entries

blob.png

可以使用访问字典或者访问对象属性的方式访问从server上获取到的attribute值,有些属性不区分大小写,raw_values获取到的是从server返回的原始的值:

 

blob.png

blob.png

blob.png

 

返回的entry可以格式化为json字符串

blob.png

如果查询的属性的值为空,返回的entries中将不包含此属性,除非在Connection中指定return_empty_attributes=False,微软AD中貌似不起作用。

blob.png

ldap server进行search操作之后,Connection有以下属性可以访问:

blob.png

 

 


猜你喜欢

转载自blog.51cto.com/9429042/2134115