You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python ldap3创建AD用户时添加密码与账户属性报错排查

问题描述

以下是用于创建AD用户的Python代码:

def create_ad_user(samaccountname, email, ou, nome='Test'):
    print(samaccountname, email, ou)

    server = Server('ldap://<my ldap server>', get_info=ALL, use_ssl=True)
    conn = Connection(server, user='<my admin user>', password='<my admin password>', auto_bind=True)

    password = 'Password123!'

    # 创建用户
    user_dn = f"CN={nome},{ou}"
    attributes = {
        "objectClass": ["top", "person", "organizationalPerson", "user"],
        "sAMAccountName": samaccountname,
        "givenName": 'Test',
        "sn": 'Test',
        "mail": email,
        "description": 'Test creazione utenti con ldap3',
        "userPrincipalName": f"{samaccountname}@ssn.local",
        "unicodePwd": f'\"{password}\"'.encode("utf-16-le"),
        "userAccountControl": 512,  # 启用账户
    }

    success = conn.add(user_dn, attributes=attributes)
    if not success:
        print(f"Errore nella creazione dell'utente: {conn.result}")
        return

    # 修改pwdLastSet属性强制下次登录修改密码
    conn.modify(user_dn, {"pwdLastSet": [(MODIFY_REPLACE, [0])]})

    print(f"Utente {samaccountname} creato con successo in {ou}.")

移除unicodePwd和userAccountControl属性时代码运行正常,但添加这两个属性后出现如下异常:

{'result': 53, 'description': 'unwillingToPerform',
'dn': '', 'message': '0000001F: SvcErr: DSID-031A12E8, problem 5003 (WILL_NOT_PERFORM)
, data 0\n\x00', 'referrals': None, 'type': 'addResponse'}

请问哪里操作出错了?


解决方案

触发WILL_NOT_PERFORM错误的核心原因是Active Directory要求设置/修改用户密码必须通过加密的LDAP连接(SSL/TLS),你的代码存在以下关键问题:

  • LDAP URL协议配置错误:使用ldap://(非加密协议,默认389端口)却启用use_ssl=True,导致无法建立有效加密通道。需将URL改为ldaps://(加密协议,默认636端口),确保AD服务器开启LDAPS服务且端口可访问:

    server = Server('ldaps://<my ldap server>', get_info=ALL, use_ssl=True)
    
  • 额外注意事项:

    • 确认AD管理员账户具备创建用户及设置密码的权限;
    • 检查密码Password123!是否符合AD的密码复杂度策略;
    • unicodePwd的编码逻辑(双引号包裹后转UTF-16-LE)是正确的,无需修改。

调整连接协议后即可正常创建带初始密码的启用状态AD用户。


内容的提问来源于stack exchange,提问作者Enrico Arnaudo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 15:15:23