使用 ldap3 2.9.1
pip install ldap3
from ldap3 import Server, Connection, SIMPLE, SYNC, ALL
import pandas as p
d
import json
# LDAP 伺服器地址
server = Server('ldap://ldap03.abc.com:389')
# 使用者名稱和密碼
username = 'xxxxxx@abc.com'
password = 'xxxxxx'
dep = '9'
# LDAP 認證
try:
# 創建連接
with Connection(server, user=username, password=password, authentication=SIMPLE, auto_bind=True) as conn:
# 認證成功
# 搜尋資料
search_filter = f'(|(department=9T21*)(department=AT21*)(department=9N24280*)(department=8Q21150*))'
conn.search(search_base='dc=abc,dc=com', search_filter=search_filter, attributes=['*'])
json_response = conn.response_to_json()
json_data = json.loads(json_response, encoding='utf-8')
# 展開每個 entry 的 attributes
df = pd.DataFrame([entry['attributes'] for entry in json_data['entries']])
if not df.empty:
## 寫回資料庫
##
except Exception as e:
# 認證失敗
print("LDAP 認證失敗:", e)