如何使用 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 和域之间的认证服务?
请问有什么好的处理方法吗?
谢谢!
最佳答案
此代码适用于 Windows 2012 R2 AD:
首先安装最新的 ldap3 包: 须藤 pip 安装 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)
关于python - 如何使用 Python 更改域用户(windows Active Directory)的密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20875708/