1

How do I change Password of a user of Active Directory using python ldap3

I am trying to create a python script what will open LDAP connection to a server running Active Directory, takes username as input and gives details like cn, email of the user. Next I am trying to update the password of the user by taking input the current password, New password from the user. All the details including name, email are correct in the output but password change is failing.

from ldap3 import Connection, Server


def fetch_email(username):
    server = Server('#####')
    con = Connection(server, user="#####r", password="#####", auto_bind=True)
    con.search("DC=rohan,DC=com", "(&(objectcategory=person)(sAMAccountName={}))".format(username), attributes=["cn","mail"])

    full_name = None
    email = None
    for entry in con.entries:
        if "cn" in entry:
            full_name_attr = entry.cn
            full_name = str(full_name_attr)  # Convert Attribute to string

        if "mail" in entry:
            email_attr = entry.mail
            email = str(email_attr)  # Convert Attribute to string

        if full_name and email:
            break

    con.unbind()
    return full_name, email


def change_password(username, current_password, new_password):
    server = Server('#####')
    con = Connection(server, user="#####", password="######", auto_bind=True)
    con.search("DC=rohan,DC=com", "(&(objectcategory=person)(sAMAccountName={}))".format(username), attributes=["cn"])

    user_dn = None
    for entry in con.entries:
        if "cn" in entry:
            user_dn = entry.entry_dn
            break

    if user_dn:
        response = con.extend.microsoft.modify_password(user_dn, new_password, current_password)
        print("Modify Password Response:", response)
        print("LDAP Result:", con.result)

        if response:
            print("Password change successful.")
        else:
            print("Password change failed.")
    else:
        print("User not found.")

    con.unbind()


# Prompt user to enter the username
username = input("Enter username: ")

current_password = input("Enter current password: ")
new_password = input("Enter new password: ")

full_name, email = fetch_email(username)
print("Full Name:", full_name)
print("Email:", email)

change_password(username, current_password, new_password)

All the details in the output are correct but Password Change is Failing.

Is there any policy which is stopping ldap3 from making changes of user password?

This is the output I am getting. LDAP Result: {'result': 53, 'description': 'unwillingToPerform', 'dn': '', 'message': '00002077: SvcErr: DSID-03190F5B, problem 5003 (WILL_NOT_PERFORM), data 0\n\x00', 'referrals': None, 'type': 'modifyResponse'} Password change failed.

Any suggestion on how to set the user password.

Rohan
  • 11
  • 2

0 Answers0