Files
TEMP_spec_system_V3/test_ldap.py
beabigegg 4f7f46b07a 2ND
2025-08-28 08:59:46 +08:00

116 lines
3.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
簡單的 LDAP 連線測試腳本
用於驗證 LDAP 設定是否正確
"""
from ldap3 import Server, Connection, ALL
import os
from dotenv import load_dotenv
# 載入環境變數
load_dotenv()
def test_ldap_connection():
"""測試 LDAP 伺服器連線"""
print("=== LDAP 連線測試 ===")
# 讀取設定
ldap_server = os.getenv('LDAP_SERVER')
ldap_port = int(os.getenv('LDAP_PORT', 389))
use_ssl = os.getenv('LDAP_USE_SSL', 'false').lower() in ['true', '1', 't']
bind_dn = os.getenv('LDAP_BIND_USER_DN')
bind_password = os.getenv('LDAP_BIND_USER_PASSWORD')
search_base = os.getenv('LDAP_SEARCH_BASE')
print(f"LDAP 伺服器: {ldap_server}")
print(f"LDAP 連接埠: {ldap_port}")
print(f"使用 SSL: {use_ssl}")
print(f"搜尋基底: {search_base}")
print(f"服務帳號 DN: {bind_dn}")
try:
# 建立伺服器連線
server = Server(ldap_server, port=ldap_port, use_ssl=use_ssl, get_info=ALL)
print(f"✅ LDAP 伺服器物件建立成功")
# 測試服務帳號連線
print("正在測試服務帳號連線...")
conn = Connection(server, user=bind_dn, password=bind_password, auto_bind=True)
if conn.bound:
print("✅ 服務帳號連線成功!")
# 測試搜尋功能
print("正在測試 LDAP 搜尋功能...")
search_filter = "(objectClass=user)"
conn.search(search_base, search_filter, attributes=['dn'], size_limit=5)
if conn.entries:
print(f"✅ LDAP 搜尋成功,找到 {len(conn.entries)} 個條目")
for entry in conn.entries[:3]:
print(f" - {entry.entry_dn}")
else:
print("⚠️ LDAP 搜尋沒有找到任何條目")
conn.unbind()
else:
print("❌ 服務帳號連線失敗")
return False
except Exception as e:
print(f"❌ LDAP 連線錯誤: {e}")
return False
print("=== LDAP 連線測試完成 ===")
return True
def test_user_authentication():
"""測試使用者認證 (需要手動輸入測試帳號)"""
print("\n=== 使用者認證測試 ===")
test_user = input("請輸入測試用帳號 (完整UPN格式如 user@domain.com): ").strip()
if not test_user or '@' not in test_user:
print("❌ 帳號格式不正確")
return False
test_password = input("請輸入測試密碼: ").strip()
if not test_password:
print("❌ 密碼不可為空")
return False
# 讀取設定
ldap_server = os.getenv('LDAP_SERVER')
ldap_port = int(os.getenv('LDAP_PORT', 389))
use_ssl = os.getenv('LDAP_USE_SSL', 'false').lower() in ['true', '1', 't']
try:
server = Server(ldap_server, port=ldap_port, use_ssl=use_ssl, get_info=ALL)
print(f"正在驗證 {test_user}...")
conn = Connection(server, user=test_user, password=test_password, auto_bind=True)
if conn.bound:
print("✅ 使用者認證成功!")
conn.unbind()
return True
else:
print("❌ 使用者認證失敗 - 帳號或密碼錯誤")
return False
except Exception as e:
print(f"❌ 認證過程發生錯誤: {e}")
return False
if __name__ == "__main__":
print("LDAP 測試工具")
print("此工具用於測試 LDAP 連線和認證功能\n")
# 測試 LDAP 連線
if test_ldap_connection():
# 如果連線測試通過,可以選擇測試使用者認證
choice = input("\n是否要測試使用者認證? (y/N): ").strip().lower()
if choice == 'y':
test_user_authentication()
input("\n按 Enter 鍵結束...")