求Python实现Active Directory用户pwdlastset值重置脚本
实现AD用户pwdLastSet属性重置的Python脚本
基于你提供的LDAP连接代码,结合示例PowerShell脚本的逻辑,以下是实现将指定用户pwdLastSet先设为0再设为-1的完整代码:
首先确保你已安装ldap3库(你的连接代码基于该库):
pip install ldap3
完整脚本:
from ldap3 import Server, Connection, ALL, MODIFY_REPLACE # 你的AD连接信息 server_address = 'xxxx' username = 'xxxx' password = 'xxxx' target_user_dn = 'CN=目标用户名,OU=用户组,DC=domain,DC=com' # 替换为目标用户的完整LDAP区分名 # 连接AD服务器 server = Server(server_address, get_info=ALL) conn = Connection(server, user=username, password=password, auto_bind=True) if conn.bind(): print('Successfully connected to Active Directory') # 第一步:将pwdLastSet设为0 try: conn.modify(target_user_dn, {'pwdLastSet': [(MODIFY_REPLACE, [0])]}) if conn.result['description'] == 'success': print('pwdLastSet已成功设为0') else: print('设置pwdLastSet为0失败:', conn.result['message']) except Exception as e: print('设置pwdLastSet为0时出错:', str(e)) # 第二步:将pwdLastSet设为-1(对应AD自动设置为当前时间) # 注:AD中pwdLastSet是64位无符号整数,PowerShell的-1等价于该十进制值 try: conn.modify(target_user_dn, {'pwdLastSet': [(MODIFY_REPLACE, [18446744073709551615])]}) if conn.result['description'] == 'success': print('pwdLastSet已成功设为-1(重置为当前时间)') else: print('设置pwdLastSet为-1失败:', conn.result['message']) except Exception as e: print('设置pwdLastSet为-1时出错:', str(e)) else: print('Failed to connect to Active Directory:', conn.result) # 关闭连接 conn.unbind()
关键说明:
- 目标用户DN获取:如果你不知道用户的完整LDAP区分名,可通过搜索获取:
# 示例:通过用户名搜索用户DN conn.search('DC=domain,DC=com', '(samAccountName=目标用户名)', attributes=['distinguishedName']) if conn.entries: target_user_dn = conn.entries[0].distinguishedName.value print(f'找到用户DN: {target_user_dn}') - pwdLastSet的特殊值:AD中
pwdLastSet设为18446744073709551615等价于PowerShell里的-1,会触发AD将密码最后修改时间设为当前系统时间。 - LDAP修改操作:使用
MODIFY_REPLACE操作符替换属性值,这是LDAP修改属性的标准方式。
内容的提问来源于stack exchange,提问作者Nathaniel Bador
相关产品推荐
相关产品推荐

