Python3禁用AD账号与重置AD账号密码ldap

Python3禁用AD账号

# LDAP服务器地址、端口号及连接参数
import ldap3
from ldap3 import Server, Connection,ALL 
import datetime
print(datetime.datetime.now())
server = Server('10.10.22.14',port=636,get_info=ALL,use_ssl=True)
# server = Server('10.10.22.14',port=389,get_info=ALL,use_ssl=False)
conn = Connection(server, user='srv-user', password='Ypassword',auto_bind=True)
print(datetime.datetime.now())
username='zdd'


#禁用ad账号
if conn.bind():

   # 设置查询条件
   #base_dn = 'OU=IT管理中心,OU=Staff,dc=test19,dc=com'
   base_dn = 'dc=test19,dc=com'
   #filterstr = "(objectClass=person)"
   filterstr=f'(&(objectClass=Person)(sAMAccountName={username}))'
   #print(filterstr)
   # 发起查询并获取结果
   result = conn.search(base_dn, filterstr, attributes=['cn', 'mail', 'distinguishedName', 'sAMAccountName','userAccountControl'])
   #print(result,conn.response)
   if result:
       res = conn.response
       entry = res[0]
       if 'raw_attributes' in entry.keys():
          samaccountname = str(entry['raw_attributes']['sAMAccountName'][0].lower(),'utf-8')
          dn = str(entry['raw_attributes']['distinguishedName'][0].lower(),'utf-8')
          uac = str(entry['raw_attributes']['userAccountControl'][0].lower(),'utf-8')
          print(dn,samaccountname,uac)

           # 禁用账户
          uac = int(uac) + 2 
          mod_attrs = {
              # 'userAccountControl': [(ldap3.MODIFY_REPLACE, [514])]  # 514 表示禁用账户,这样写会丢失某些属性,比如密码永不过期
              'userAccountControl':[(ldap3.MODIFY_REPLACE,[uac])]
          }
          conn.modify(dn, mod_attrs)
           
          # 检查修改是否成功
          if conn.result["description"] == "success":
              print(f"Account {dn} has been disabled.")
          else:
              print(f"Failed to disable account {dn}.")
              print(conn.result["description"] )

       else:
           print(f"{username} not found.")
   else:
       print("No entries found.")

else:
    print("Failed to bind with the server.")

# 关闭连接
conn.unbind()

 

Python3使用管理员权限重置AD账号密码

# LDAP服务器地址、端口号及连接参数
import ldap3
from ldap3 import Server, Connection,ALL 
server = Server('10.10.22.14',port=636,get_info=ALL,use_ssl=True)  #修改密码需要使用ldaps
conn = Connection(server, user='admin', password='yyy',auto_bind=True)

username='zdx'
new_pwd='Y111'

if conn.bind():

   # 设置查询条件
   #base_dn = 'OU=IT,OU=SOU,dc=test19,dc=com'
   base_dn = 'dc=test19,dc=com'
   #filterstr = "(objectClass=person)"
   filterstr=f'(&(objectCategory=Person)(objectClass=User)(sAMAccountName={username}))'
   #print(filterstr)
   # 发起查询并获取结果
   result = conn.search(base_dn, filterstr, attributes=['cn', 'mail', 'distinguishedName', 'sAMAccountName', 'userAccountControl'])
   #print(result,conn.response)
   if result:
       res = conn.response
       entry = res[0]
       if 'raw_attributes' in entry.keys():
          samaccountname = str(entry['raw_attributes']['sAMAccountName'][0].lower(),'utf-8')
          dn = str(entry['raw_attributes']['distinguishedName'][0].lower(),'utf-8')
          uac = str(entry['raw_attributes']['userAccountControl'][0].lower(),'utf-8')  #获取用户UAC值
          print(dn,samaccountname,uac)

          pwd_change={
            #'userPassword':[(ldap3.MODIFY_REPLACE,[new_pwd])],  #该代码会将明文密码写入到账号属性UserPassword中
            'unicodePwd':[(ldap3.MODIFY_REPLACE,[f'"{new_pwd}"'.encode('utf-16-le')])],
            'userAccountControl':[(ldap3.MODIFY_REPLACE,[uac])]
          }

          conn.modify(dn,pwd_change)
           

       else:
           print(f"{username} not found.")
   else:
       print("No entries found.")

else:
    print("Failed to bind with the server.")

# 关闭连接
conn.unbind()

 

设置 用户下次登录需要修改密码

# LDAP服务器地址、端口号及连接参数
import ldap3
from ldap3 import Server, Connection,ALL 
import datetime
print(datetime.datetime.now())
# server = Server('10.1.22.14',port=636,get_info=ALL,use_ssl=True)
server = Server('10.1.22.14',port=389,get_info=ALL,use_ssl=False)
conn = Connection(server, user='username', password='password',auto_bind=True)
print(datetime.datetime.now())
username='zdx'

if conn.bind():

   # 设置查询条件
   base_dn = 'dc=test19,dc=com'
   #filterstr = "(objectClass=person)"
   filterstr=f'(&(objectCategory=Person)(objectClass=User)(sAMAccountName={username}))'
   #print(filterstr)
   # 发起查询并获取结果
   result = conn.search(base_dn, filterstr, attributes=['cn', 'mail', 'distinguishedName', 'sAMAccountName'])
   #print(result,conn.response)
   if result:
       res = conn.response
       entry = res[0]
       if 'raw_attributes' in entry.keys():
          samaccountname = str(entry['raw_attributes']['sAMAccountName'][0].lower(),'utf-8')
          dn = str(entry['raw_attributes']['distinguishedName'][0].lower(),'utf-8')
          print(dn,samaccountname)

           # 设置 用户下次登录需要修改密码
          mod_attrs = {
              'pwdLastSet': [(ldap3.MODIFY_REPLACE, [0])]  # 0 表示“用户下次登录需要修改密码”,-1 取消“用户下次登录需要修改密码”
          }
          conn.modify(dn, mod_attrs)
           
          # 检查修改是否成功
          if conn.result["description"] == "success":
              print(f"Account {dn} has been set password expired.")
          else:
              print(f"Failed to set password expired {dn}.")

       else:
           print(f"{username} not found.")
   else:
       print("No entries found.")

else:
    print("Failed to bind with the server.")

# 关闭连接
conn.unbind()

 

 

参考:https://blog.51cto.com/u_13366251/7418664

https://www.cnblogs.com/cptao/p/15515047.html 使用旧密码修改新密码

 

posted on 2024-07-16 16:29  momingliu11  阅读(34)  评论(0编辑  收藏  举报