Listing Active Directory Users Using Python

April 25, 2017 · By Preston Rohner · Networking · Programming · Python

Sometimes it’s nice to be able to take a quick look at your Active Directory (AD) users and see what’s there and who is actually active. Here’s a quick little Python program to list out your current users.

It’s not a very heavy duty program thanks to the ldap3 module. You can install the module easily using pip install ldap3. The project page has more info and documentation.

We start off by setting variables with our custom values that we are going to need to use in the program. I would imagine that it’s obvious that you should replace the values used in the assignments with your own values.

 

server_name = 'your_server'
domain_name = 'your_domain'
user_name = 'your_username'
password = 'your_password'

Next we create an instance of the LDAP3 Server class. We can then use the server as a parameter to the Connection. Once we have our connection instance then we can perform a search in AD. The key is that we are querying for (objectclass=person). That will give us the person objects from AD. Then it’s a quick little loop to display all of the results. Here’s the code:

 

import sys
from ldap3 import Server, Connection, ALL, NTLM, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES, AUTO_BIND_NO_TLS, SUBTREE
from ldap3.core.exceptions import LDAPCursorError

server_name = 'your_server'
domain_name = 'your_domain'
user_name = 'your_username'
password = 'your_password'

format_string = '{:25} {:>6} {:19} {:19} {}'
print(format_string.format('User', 'Logins', 'Last Login', 'Expires', 'Description'))

server = Server(server_name, get_info=ALL)
conn = Connection(server, user='{}\\{}'.format(domain_name, user_name), password=password, authentication=NTLM, auto_bind=True)
conn.search('dc={},dc=local'.format(domain_name), '(objectclass=person)', attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
for e in conn.entries:
    try:
        desc = e.description
    except LDAPCursorError:
        desc = ""

print(format_string.format(str(e.name), str(e.logonCount), str(e.lastLogon)[:19], str(e.accountExpires)[:19], desc))

If you would like to perform more complex searches there is a set of basic syntax for querying. The project page provides more details on searching the Directory Information Tree.

The list_users program code is all yours to use.

When have you had to dig through your AD and see who is doing what?