Useful LDAP Queries against Active Directory
Useful LDAP Queries against Active Directory
LDAP Search Examples Using ldapsearch
I want to share some useful LDAP queries that can be executed against directory services using the ldapsearch utility. The examples listed below were tested against an Active Directory Domain Controller Global Catalog.
1. Get Specific Attributes from a Search Filter
1
2
3
4
5
6
7
8
9
ldapsearch -LLL \
-H ldap://x.x.x.x:3268/ \
-x \
-D "test@domain.com" \
-w 123456 \
-b "dc=com" \
-s sub \
'(&(objectClass=user)(sAMAccountName=sghaida))' \
dn cn title sAMAccountName userPrincipalName mail
This query retrieves only specific attributes for a user matching the given sAMAccountName.
2. Search User by Email (Exclude Contacts)
This query searches for a user by email address while excluding any objects that inherit from the contact object class.
1
2
3
4
5
6
7
8
ldapsearch -L \
-b "dc=com" \
-D "test@domain.com" \
-x \
-w 123456 \
-h 10.1.0.75 \
-p 3268 \
"(&(!(objectClass=contact))(objectClass=user)(mail=$1))"
3. Search Users by sAMAccountName (Exclude Computers)
In Active Directory, machines are also represented as users. This query excludes objects that inherit from the computer object class.
1
2
3
4
5
6
7
8
ldapsearch -L \
-b "dc=com" \
-D "test@domain.com" \
-x \
-w 123456 \
-h 10.1.0.75 \
-p 3268 \
"(&(!(objectClass=computer))(objectClass=user)(sAMAccountName=$1))"
4. Get Email Addresses for a Specific UPN
The following Bash script retrieves email addresses associated with a specific userPrincipalName.
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
email=$(ldapsearch \
-b "dc=com" \
-D "DOMAIN\\test" \
-x \
-w 123456 \
-h x.x.x.x \
-p 3268 \
"(userPrincipalName=$1)" | \
grep ^mail: | awk '{printf $2" "}')
echo -e " $1 $email "
This post is licensed under CC BY 4.0 by the author.