一、Pythonldap安裝
Python-ldap是Python編程語言的LDAP接口。它允許Python程序訪問LDAP目錄服務器。在使用Python-ldap之前,需要對其進行安裝。
使用pip工具進行安裝:
pip install python-ldap
如果想從源代碼進行安裝,可以從Python-ldap的官方網站上下載並安裝:
tar xvfz python-ldap.tgz
cd python-ldap-X.Y.Z
python setup.py build
python setup.py install
二、Python ldap3 查詢 用戶
使用Python ldap3庫中的Connection.search()方法可以進行LDAP的搜索。以下為一個ldap查詢的示例:
import ldap3
server = ldap3.Server('example.com', use_ssl=True)
conn = ldap3.Connection(server, user='cn=admin,dc=example,dc=com', password='password')
with conn:
conn.search(
search_base='ou=People,dc=example,dc=com',
search_filter='(uid=jdoe)',
search_scope=ldap3.SEARCH_SCOPE_WHOLE_SUBTREE,
attributes=ldap3.ALL_ATTRIBUTES)
if conn.entries:
user_dn = conn.entries[0].entry_dn
print(user_dn)
三、Pythonldap同步group
Python ldap3庫也可以用來同步組信息。使用Connection.extend.microsoft.add_members_to_groups()方法可以添加成員到組中:
import ldap3
server = ldap3.Server('example.com', use_ssl=True)
conn = ldap3.Connection(server, user='cn=admin,dc=example,dc=com', password='password')
with conn:
conn.extend.microsoft.add_members_to_groups(
group_dn='cn=group,ou=Groups,dc=example,dc=com',
members_dns=['cn=jdoe,ou=People,dc=example,dc=com'])
四、Python ldap3文檔
Python ldap3文檔提供了詳細的使用指南和API文檔,以及示例代碼和FAQ等信息。可以從Python ldap3官方網站上查看:https://ldap3.readthedocs.io/en/latest/
五、Python ldapsearch
ldapsearch是一個命令行工具,用於搜索和顯示LDAP目錄信息。Python ldap3庫可以通過Connection.search()方法實現類似的功能:
import ldap3
server = ldap3.Server('example.com', use_ssl=True)
conn = ldap3.Connection(server, user='cn=admin,dc=example,dc=com', password='password')
with conn:
conn.search(
search_base='dc=example,dc=com',
search_filter='(objectClass=*)',
search_scope=ldap3.SEARCH_SCOPE_BASE_OBJECT)
六、Python ldap3中文文檔
Python ldap3文檔提供了中文版本,提供了完成信息,可以查看:https://ldap3-cn.readthedocs.io/zh_CN/latest/
七、Python ldap3 讀取用戶dn
使用Python ldap3庫中的Connection.search()方法可以查詢用戶dn:
import ldap3
server = ldap3.Server('example.com', use_ssl=True)
conn = ldap3.Connection(server, user='cn=admin,dc=example,dc=com', password='password')
with conn:
conn.search(
search_base='ou=People,dc=example,dc=com',
search_filter='(uid=jdoe)',
search_scope=ldap3.SEARCH_SCOPE_WHOLE_SUBTREE,
attributes=['dn'])
if conn.entries:
user_dn = conn.entries[0]['dn'].value
print(user_dn)
八、Python ldap3 統計ad數據
使用Python ldap3庫的一些方法可以方便地統計獲得LDAP目錄中的數據,如下所示:
import ldap3
server = ldap3.Server('example.com', use_ssl=True)
conn = ldap3.Connection(server, user='cn=admin,dc=example,dc=com', password='password')
with conn:
conn.search(
search_base='dc=example,dc=com',
search_filter='(objectClass=*)',
search_scope=ldap3.SEARCH_SCOPE_BASE_OBJECT,
attributes=['numSubordinates', 'namingContexts'])
naming_contexts = conn.entries[0]['namingContexts'][0].value
num_users = int(conn.entries[0]['numSubordinates'].value) - 2
print('Naming contexts:', naming_contexts)
print('Number of users:', num_users)
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/199533.html