一尘不染

如何使用Python更改域用户(Windows Active Directory)的密码?

python

如何使用Python更改域用户的密码?我板上有ldap模块,但没有解决方案。我设法通过ldap查询当前设置,但是如何修改呢?

import ldap
import sys

host = 'ldap://10.172.0.79'

con = ldap.initialize(host)
BIND_DN = "administrator@biztalk.com"
BIND_PASS = "a-123456"
con.set_option( ldap.OPT_X_TLS_DEMAND, True )
con.set_option( ldap.OPT_DEBUG_LEVEL, 255 )

PASSWORD_ATTR = "unicodePwd"
username="bizadmin"
user_dn = "CN=%s,OU=User,OU=biztalk,DC=biz-talk,DC=com" % username
password = 'New12345'

# Set AD password
unicode_pass = unicode("\"" + password + "\"", "iso-8859-1")
password_value = unicode_pass.encode("utf-16-le")
add_pass = [(ldap.MOD_REPLACE, PASSWORD_ATTR, [password_value])]

# Replace password
try:
    con.modify_s(user_dn, add_pass)
    print "Active Directory password for", username, "was set successfully!"
except ldap.LDAPError, e:
    sys.stderr.write('Error setting AD password for: ' + username + '\n')
    sys.stderr.write('Message: ' + str(e) + '\n')
    sys.exit(1)

错误

pydev调试器:启动

为bizadmin设置AD密码时出错

消息:{‘desc’:“无法联系LDAP服务器”}


Python更改域(Microsoft Active Directory)用户的密码。

…需要python和域之间的认证服务?

您有什么好办法可以解决吗?

谢谢!


阅读 643

收藏
2021-01-20

共1个答案

一尘不染

这段代码适用于Windows 2012 R2 AD:

首先安装最新的ldap3软件包:sudo pip install ldap

#!/usr/bin/python

import ldap3

SERVER='127.0.0.1'
BASEDN="DC=domain,DC=com"
USER="user_domain_login_name@domain.com"
CURREENTPWD="current_password"
NEWPWD="new_password"

SEARCHFILTER='(&(userPrincipalName='+USER+')(objectClass=person))'

USER_DN=""
USER_CN=""

ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL)
conn = ldap3.Connection(ldap_server, USER, CURREENTPWD, auto_bind=True)
conn.start_tls()
#print conn
conn.search(search_base = BASEDN,
         search_filter = SEARCHFILTER,
         search_scope = ldap3.SUBTREE,
         attributes = ['cn', 'givenName', 'userPrincipalName'],
         paged_size = 5)

for entry in conn.response:
    if entry.get("dn") and entry.get("attributes"):
        if entry.get("attributes").get("userPrincipalName"):
            if entry.get("attributes").get("userPrincipalName") == USER:
                USER_DN=entry.get("dn")
                USER_CN=entry.get("attributes").get("cn")

print "Found user:", USER_CN
print USER_DN
print ldap3.extend.microsoft.modifyPassword.ad_modify_password(conn, USER_DN, NEWPWD, CURREENTPWD,  controls=None)
2021-01-20