Django用户同步至LDAP服务器异常:连接成功仍报WinError10060
Django用户同步LDAP问题排查与修复
问题现象
我试图将Django中创建的用户同步到LDAP服务器,控制台虽打印了「LDAP连接成功」,但后续添加用户的操作无法完成,还抛出以下错误:
LDAP connection successfully. Error occurred during LDAP connection: ('unable to open socket', [(LDAPSocketOpenError('socket connection error while opening: [WinError 10060]
另外,反向操作(通过当前连接将LDAP用户导入数据库)可以正常执行。
实现代码
def create_user_in_ldap(request, django_user): """ 将Django中创建的用户添加到LDAP服务器。 """ try: ldap_config = get_object_or_404(LdapConfig,company=request.user.company) ldap_server = ldap_config.ldap_server ldap_username = ldap_config.bind_username ldap_password = ldap_config.bind_password ldap_domain = ldap_config.bind_dn server = Server(ldap_server, get_info=ALL) connection = Connection( server, user=f"{ldap_domain}\\{ldap_username}", password=ldap_password, authentication=NTLM, auto_bind=True ) if not connection.bind(): print(f"LDAP连接失败: {connection.result}") return False print("LDAP连接成功") user_dn = f"cn={django_user.username},ou=Users,dc=example,dc=com" attributes = { "objectClass": ["top", "person", "organizationalPerson", "user"], "cn": django_user.username, "sn": django_user.last_name or "无姓氏", "givenName": django_user.first_name or "无名字", "displayName": f"{django_user.first_name} {django_user.last_name}", "mail": django_user.email, "userPassword": "default_password", } connection.add(user_dn, attributes=attributes) print("用户添加结果:", connection.result) if connection.result["description"] == "success": print(f"用户 {django_user.username} 成功添加到LDAP服务器") return True else: print(f"添加用户失败: {connection.result['description']}") return False except Exception as e: print(f"LDAP连接过程中出错: {str(e)}") return False
问题排查与修复建议
1. 移除重复绑定操作
你设置了auto_bind=True,这会在创建Connection实例时自动完成绑定,后续调用connection.bind()属于重复操作,可能导致连接状态异常。直接删除这段冗余判断:
# 移除以下代码块 # if not connection.bind(): # print(f"LDAP连接失败: {connection.result}") # return False
2. 解决WinError 10060连接超时
该错误表示LDAP服务器地址/端口无法正常访问,即使初始绑定看似成功,后续操作时连接已断开。检查以下项:
- 确认
ldap_server地址包含正确端口:默认LDAP用389,LDAPS用636,格式应为ldap://xxx.com:389或ldaps://xxx.com:636 - 验证Django服务器到LDAP服务器的防火墙规则,确保对应端口开放
- 若使用LDAPS,需确认Windows环境已导入LDAP服务器证书到系统信任库
3. 修正LDAP用户属性与DN
- 确认
ou=Users,dc=example,dc=com组织单元(OU)在LDAP服务器中真实存在,不存在则需提前创建 - 针对AD LDAP,
userPassword属性不适用,需替换为unicodePwd,且密码需符合AD复杂度要求,同时用UTF-16LE编码:
attributes = { # 保留其他属性 "unicodePwd": ("\"default_password\"").encode('utf-16-le'), }
4. 细化异常捕获
当前宽泛的异常捕获不利于定位问题,拆分LDAP专属异常:
from ldap3.core.exceptions import LDAPSocketOpenError, LDAPBindError, LDAPAddError try: # 现有代码逻辑 except LDAPSocketOpenError as e: print(f"LDAP套接字连接失败: {str(e)}") return False except LDAPBindError as e: print(f"LDAP绑定失败: {str(e)}") return False except LDAPAddError as e: print(f"添加LDAP用户失败: {str(e)}") return False except Exception as e: print(f"未知错误: {str(e)}") return False
内容的提问来源于stack exchange,提问作者Serkan
相关产品推荐
相关产品推荐

