pythonを使用してldapのすべてのユーザーを取得する方法
LDAP(Lightweight Directory Access Protocol)からすべてのユーザーを取得するには、python-ldapライブラリを使用できます。
最初に、python-ldapライブラリがインストールされていることを確認してください。以下のコマンドを使用してインストールできます:
pip install python-ldap
LDAPサーバへの接続方法と全てのユーザ情報を取得する方法を以下に示すコードで説明します。
import ldap
# 连接到LDAP服务器
ldap_server = 'ldap://your_ldap_server' # 替换为实际的LDAP服务器地址
ldap_base_dn = 'dc=example,dc=com' # 替换为实际的LDAP基础DN
ldap_user = 'cn=admin,dc=example,dc=com' # 替换为实际的LDAP管理员用户
ldap_password = 'password' # 替换为实际的LDAP管理员用户密码
conn = ldap.initialize(ldap_server)
conn.simple_bind_s(ldap_user, ldap_password)
# 搜索所有用户
search_filter = '(objectClass=person)'
search_attribute = ['cn', 'mail'] # 指定要获取的属性列表
results = conn.search_s(ldap_base_dn, ldap.SCOPE_SUBTREE, search_filter, search_attribute)
# 打印用户信息
for dn, attrs in results:
print('User DN:', dn)
for attr, values in attrs.items():
print(attr + ':', values)
# 断开LDAP连接
conn.unbind()
上のサンプルコードでは、まずldap.initialize()メソッドでLDAP接続を初期化し、conn.simple_bind_s()メソッドで認証を行っています。次に、conn.search_s()メソッドを使ってすべてのユーザを検索しています。検索時には、検索するベースDN、検索範囲、検索フィルタ、取得する属性リストを指定しています。最後に、forループで結果を走査し、各ユーザの属性情報を表示しています。
サンプルコード内の LDAP サーバーアドレス、ベース DN、管理者ユーザーおよびパスワードは、実際の環境に合わせて置き換えてください。