Useful ldapsearch Examples

Use practical ldapsearch commands for users, groups, attributes, scopes, paging, TLS, and troubleshooting across common LDAP directories.

On this page

What is ldapsearch and When Should You Use It?

ldapsearch is a command-line utility included with OpenLDAP and similar LDAP toolkits, purpose-built for querying directory servers using the LDAP protocol. It retrieves directory information such as users, groups, and schema definitions. Unlike graphical tools or proprietary vendor CLI utilities, ldapsearch is:

  • Granular: Exposes full control of scope, filter logic, and attribute selection.
  • Scriptable: Easily automated for integration and batch operations.
  • Standardized: Avoids dependency on environment-specific or vendor-locked solutions.

This makes it indispensable for developers, system administrators, and identity engineers needing transparent, reproducible directory queries—especially for automation, debugging, and cross-platform integration.

Understanding the ldapsearch Command: Anatomy and Key Options

A typical ldapsearch command is built from several core parameters. According to the OpenLDAP documentation:

  • Base DN (-b): The directory subtree from which searches begin (e.g., -b dc=example,dc=com). Omitting this may defer to the server’s default context.
  • Filter: Defines which entries are matched; must always be present (e.g., (objectClass=inetOrgPerson)).
  • Attribute list: Define specific attributes to return (e.g., cn mail), or omit for most attributes by default.
  • Authentication options: Important flags include:
    • -D: Bind DN (identity to authenticate as)
    • -w: Password (insecure—will be visible to other processes)
    • -W: Prompt for password interactively (safer)
    • -y: Read password from a file (safer)

Each command needs at least a base DN and filter. Output attributes are optional but recommended for privacy and clarity.

Authentication with ldapsearch: Secure Practice and Common Pitfalls

LDAP directories commonly require authentication for most queries. You can combine anonymous, simple, or SASL/Kerberos binds, each with distinct patterns and recommendations.

Authentication types:

TypeInvocation ExampleTypical Uses
Anonymous bindNo -D or password option suppliedAccess to public or non-sensitive data
Simple bind-D cn=admin,dc=example,dc=com -W (prompted password)Routine queries over secure channels
SASL/Kerberos-Y GSSAPI (using SASL mechanisms; option omitted if not needed)SSO, enterprise environments
  • Anonymous bind: No credentials; only suitable where server policy allows unauthenticated access.
  • Simple bind: Bind DN and password; advised only over encrypted connections (e.g., LDAPS or StartTLS).
  • SASL/Kerberos: Mechanisms like GSSAPI for network SSO; invoked with -Y, demands environment configuration.

Secure password handling:

  • -W prompts for the password at runtime (recommended).
  • -y <file> reads the password from a local file (recommended for automation).
  • Avoid -w (password on command line)—as per OpenLDAP, this risks accidental exposure via system process lists or shell history.

Supplying invalid or no credentials typically results in failed authentication and access denied, with specific error messages provided by the directory server.

Practical ldapsearch Examples: User, Group, and Schema Queries

Anonymous vs. Authenticated Searches

Anonymous search:

bash
ldapsearch -b dc=example,dc=com "(objectClass=inetOrgPerson)"

Retrieves all users of class inetOrgPerson from dc=example,dc=com without authentication; only works if the server allows anonymous queries.

Authenticated search (simple bind, prompt for password):

bash
ldapsearch -D "cn=admin,dc=example,dc=com" -W -b dc=example,dc=com "(objectClass=inetOrgPerson)"

Prompts for the admin password, then performs the search with proper privileges.

Authenticated search (simple bind, password from file):

bash
ldapsearch -D "cn=admin,dc=example,dc=com" -y /path/to/password.txt -b dc=example,dc=com "(objectClass=inetOrgPerson)"

Supplies the password securely from a file.

Attribute-Scoped User Query

Fetch only the mail and uid attributes for a named user:

bash
ldapsearch -D "cn=admin,dc=example,dc=com" -W -b dc=example,dc=com "(cn=Alice Smith)" mail uid

Group Query (OpenLDAP)

Return all group entries using the standard object class:

bash
ldapsearch -b dc=example,dc=com "(objectClass=groupOfNames)"

Active Directory-Specific User Query

Active Directory often uses objectClass=user and attributes like sAMAccountName. For example, to retrieve user Alice’s account and email:

bash
ldapsearch -D "CN=Administrator,CN=Users,DC=ad,DC=example,DC=com" -W -b "DC=ad,DC=example,DC=com" "(sAMAccountName=alice)" mail sAMAccountName

Replace the bind DN and base DN with appropriate administrative credentials and AD domain components.

In summary, begin with anonymous searches if possible, escalate to authenticated queries for protected data, and always adapt attribute selection to avoid exposing unnecessary information.

Mastering LDAP Filters: AND, OR, NOT, and Wildcards

LDAP filters—fully standardized and supported by OpenLDAP—define powerful logic for matching directory entries. Each filter uses parenthetical syntax per RFC and OpenLDAP guidelines.

Basic equality match:

text
(objectClass=inetOrgPerson)

Substring (wildcard) match:

text
(cn=Al*)

Finds entries with common names beginning with “Al”.

Compound (logical) filters:

  • AND: &—entry must match all conditions.
    (&(objectClass=inetOrgPerson)(mail=alice@example.com))
    
    Returns users of class inetOrgPerson whose mail equals the value.
  • OR: |—entry matches if any sub-filter matches.
    (|(sn=Smith)(sn=Jones))
    
    Returns entries where surname is Smith or Jones.
  • NOT: !—entry matches if the sub-filter does not match.
    (!(mail=*))
    
    Returns entries without a mail attribute.

These operators can be nested for complex queries. Filter syntax is consistent across RFC-compliant servers and OpenLDAP.

Filter construction tips:

  • Enclose compound filters in a single set of parentheses.
  • Ensure attributes and object classes are valid for your directory schema.
  • Errors in filter syntax or unsupported attributes can yield empty output or search errors.

Interpreting Output: Reading LDIF and Understanding Results

ldapsearch output is in LDAP Data Interchange Format (LDIF), with each entry consisting of:

ldif
dn: uid=asmith,ou=users,dc=example,dc=com
uid: asmith
mail: asmith@example.com
  • Each block starts with the entry’s DN followed by attribute-value pairs.
  • Only requested or default attributes appear.
  • Entries are separated by blank lines.
  • The structure matches the LDIF specification described by OpenLDAP.

Understanding specific records (e.g., user or group) depends on both the filter used and the attribute set requested in your command.

Troubleshooting Common ldapsearch Problems

Common ldapsearch errors often include messages (sent to stderr) and numeric result codes. Here are representative issues and remedies:

  • Invalid DN syntax (34):

    ldapsearch: ldap_search: Invalid DN syntax (34)
    

    Cause: The bind DN or base DN is ill-formed (e.g., missing components or typos).
    Fix: Double-check DN formatting; ensure commas and components are present and correct.

  • Invalid credentials (49):

    ldap_bind: Invalid credentials (49)
    

    Cause: Wrong password, misspelled bind DN, or unauthorized account.
    Fix: Re-enter credentials; verify the bind DN; confirm account permissions.

  • No such object (32):

    ldap_search: No such object (32)
    

    Cause: The search base does not exist, or the DN tree is misaligned.
    Fix: Use -b with the correct directory root or container DN.

  • Filter syntax error:

    ldap_search: Bad search filter (87)
    

    Cause: Malformed filter syntax, stray parentheses, or unsupported filter types.
    Fix: Validate filter string with simple test queries; refer to documentation or previously working patterns.

Debugging tip:
Invoke ldapsearch with -d <level> to increase verbosity (e.g., -d 1 or higher). This prints detailed network, bind, and parsing diagnostics to stderr, aiding in root-cause analysis.

Always validate:

  • The base DN matches your intended directory scope.
  • The filter syntax is correct and uses known attribute names.
  • The bind DN and password are valid for the operation.
  • The server allows the type of bind or search you’re attempting.

Security Warnings and Best Practices for ldapsearch

  • Password safety:
    Never supply passwords directly on the command line with -w. Prefer -W (prompt interactively) or -y <file> (read from file for automation) to minimize risk of credential exposure, as advised in the OpenLDAP manual.
  • Attribute minimization:
    Restrict output to needed attributes to avoid leaking sensitive or excessive directory data.
  • Encrypted connections:
    Use simple binds only over TLS/SSL to prevent exposure of credentials or data in plaintext transmissions.
  • Distinction of password options:
    -w reads password from the command line (insecure);
    -W prompts for password (secure);
    -y <file> reads password from a file (secure for scripting).

Further Reading and Authoritative Resources

For comprehensive syntax, server configuration, details about authentication types, advanced filters, LDIF interpretation, and password handling, consult the OpenLDAP Administrator's Guide and official ldapsearch manual pages.

Sources