Here is a basic Python script to query Active Directory using the “ldap3” library. Useful script code for authentication.
import ldap3
server = ldap3.Server("ldap://hostname:port/")
conn = ldap3.Connection(server, "CN=username,DC=domain,DC=com", "password")
conn.bind()
query = "(&(objectCategory=person)(objectClass=user)(cn=*))"
conn.search("DC=domain,DC=com", query, attributes=["cn", "mail", "memberOf"])
result = conn.response
for item in result:
print(item["attributes"])
conn.unbind()
Replace the placeholders with the appropriate values for your Active Directory:
- “hostname” and “port” are the address and port of the Active Directory server
- “username” is the username of an account with permission to search the directory
- “password” is the password for the account
- “domain” is the domain name of your Active Directory
- “cn=*” can be modified to search for specific common names.
The “attributes” list in the conn.search()
call can be modified to retrieve other properties of the users in the directory.