Detect if an Active Directory user account is locked using LDAP in Python

Viewed 76466

I'm validating user logins using python's ldap module. When the login fails, I get a ldap.INVALID_CREDENTIALS login, but this can be either because of a wrong password or because the account is locked. The account get's locked after the 3rd try.

I would like to detect that the account is locked and report that to the frustrated user, instead of the same "invalid login" message.

Searching for a solution I found:

  • The userAccountControl LOCKED flag is not used by AD;
  • The lockoutTime attribute should be used instead

The LDAP query I should be using to find locked users is:

(&(objectClass=user)(lockoutTime>=1))

Or for a specific user:

(&(objectClass=user)(sAMAccountName=jabberwocky)(lockoutTime>=1))

But this is not working, the query returns no results every time.

7 Answers

Do it like this:

def islocked(self, user, basedn, conn):

    search_filter = "(&(objectCategory=Person)(objectClass=User)(lockoutTime>=1))"
    search_attribute = ["sAMAccountName"]

    try:
        conn.search(basedn,
                        search_filter,
                        attributes=search_attribute)
        results = conn.entries
    except ldap3.core.exceptions.LDAPException as e:
        print(e)
    lockedaccounts = [x['sAMAccountName'] for x in results]
    lockedaccounts = [str(x) for x in lockedaccounts]
    lockedaccounts = [x for x in lockedaccounts]
    if user in lockedaccounts:
        return True
    else:
        return False
Related