Sun Java logo     Previous      Contents      Index      Next     

Sun logo
Sun ONE Directory Server Resource Kit 5.2 Tools Reference 

Chapter 3
The ldapsearch Tool

The ldapsearch tool issues search requests to an Lightweight Directory Access Protocol (LDAP) directory and displays the result as LDAP Data Interchange Format (LDIF) text. Its many options allow you to perform different types of search operations, from simple entry retrieval to advanced searches that involve security or directory referrals. This chapter provides instructions on how to use the ldapsearch tool. It contains the following sections:


ldapsearch is a command-line tool that opens a connection to an LDAP server, binds to it, and performs a search using a filter. The results are then displayed in the LDIF.


The LDIF is used to represent LDAP entries in a simple text format. See Appendix E, “LDAP Data Interchange Format,” in the Sun ONE Directory Server Reference Manual for more information.

The ldapsearch tool is also provided with Sun™ ONE Directory Server in the DirectoryServer_base/shared/bin directory. However, the DSRK and its updates should include the latest version of the tool in the DSRK_base/bin/dsrk52 directory.


If you use the Solaris™ operating environment, there may be an older version of ldapsearch in /usr/bin. Be sure your path is set to use the latest version in DSRK_base/bin/dsrk52.

Command Usage

A search involves binding and possibly authenticating to a directory server before initiating a search operation with a certain scope from a given base DN. The request includes a filter of the attribute values that must match in the entries returned. The command-line options allow you to sort the results, limit how much information is returned, control how referrals are followed, enable a secure connection, and set a time limit for the operation. Results of the search are displayed as LDIF text to the standard output. By default, the results contain the DN and all attributes for each entry found by the search. The results may also be reformatted using command-line options.


The syntax of the ldapsearch tool on the command line can take any of these forms:

ldapsearch -b "baseDN" [ options ]  "filter"  [ attributeName ... ]

ldapsearch -b "baseDN" [ options ]  -f filterFile  [ attributeName ...]



The ldapsearch tool has four types of options:

The following sections detail these options. The ldapsearch -H command and option when run on the command line will display brief descriptions of all the command-line options.

Common Options

The common options listed in Table 3-1 control the binding and general behavior of the ldapsearch command.

Table 3-1  Common Options for ldapsearch 






Specify the hostname of the directory server. When this option is omitted, the default is localhost.



Specify the port number for accessing the directory server host. The default is 389 normally and 636 when the SSL options are used.



Specify a bind DN for accessing your directory, usually in double quotes ("") for the shell. If the bind DN and its password are omitted, the tool will use anonymous binding. The bind DN determines what entries and attributes will appear in the search results, according to the DN’s access permissions.



Specify the password for the bind DN. CAUTION: Specifying the password on the command-line is a possible security risk.



Type the password for the bind DN when prompted. This is the most secure way of specifying the password.



Specify a file containing the password for the bind DN. Use this option in scripts and place the password in a secure file to protect it. This option is mutually exclusive with the -w option.



Specify the base DN for the search operation, usually in double quotes ("") for the shell. You may omit this option if you specify the base DN in the LDAP_BASEDN environment variable.



Specify the scope of a search. The scope parameter may have one of the following values:

  • base - For searching only the base entry.
  • one - For searching only the children of the base entry.
  • sub - For searching the base entry and all its descendants. This is the default if the -s option is omitted.



Specify the name of a file containing filter strings. This file contains one or more filters, each on a separate line; ldapsearch will perform a separate search with each filter, in the order found in the file.



Specify the maximum number of seconds to wait for a search request to complete. Regardless of the value specified here, ldapsearch will never wait longer than is allowed by the server’s nsslapd-timelimit attribute, whose default is 3,600 seconds. For more information, see “nsslapd-timelimit (Time Limit)” in Chapter 4 of the Sun ONE Directory Server Reference Manual.



Specify the LDAP protocol version number to be used for the search operation, either 2 or 3. LDAP v3 is the default; only specify LDAP v2 when connecting to servers that do not support v3.



Specify the proxy DN to use for the search operation, usually in double quotes ("") for the shell. For more information about proxy authorization, see Chapter 6, “Managing Access Control,” in the Sun ONE Directory Server Administration Guide.



Specify how aliases are dereferenced when encountered in a search. Note that Sun ONE Directory Server 5.2 and previous versions do not support aliases, so this option has no effect on these servers. The parameter may be one of the following values:

  • never - Aliases are never dereferenced; this is the default.
  • find - Aliases are dereferenced only while finding the base DN.
  • search - Aliases are dereferenced when searching entries below the base DN (but not when finding the base DN).
  • always - Aliases are dereferenced both when finding the base DN and searching beneath it.



Manage smart referrals: when referrals are part of the search results, return the actual entry containing the referral instead of the entry obtained by following the referral. See “Creating Smart Referrals” in Chapter 2 of the Sun ONE Directory Server Administration Guide.



(Capital letter O) Specify the maximum number of referral hops to follow while searching.



Specify that referrals should not be followed. By default, referrals are followed automatically.



Verbose output mode: the tool will display additional information about the search, such as the filter string and the number of results for each search.



No-op mode: use with the -v option to show what the tool would do with the given input but do not actually perform the search.



Allow runtime library version mismatches. When this option is omitted, the default behavior is to assert that the revision number of the LDAP API is greater than or equal to that used to compile the tool. Also, if the API library and the tool have the same vendor name, the tool will also assert that the vendor version number of the API is greater than or equal to that used to compile the tool. This information is based on the contents of the LDAPAPIInfo structure. (See the Sun ONE LDAP SDK for C Programming Guide.)



Display the usage help text that briefly describes all options.

Input And Output Options

The input and output options listed in Table 3-2 control how the ldapsearch results are sorted and presented.

Table 3-2  Input and Output Options for ldapsearch 






Specify the character set to use for command-line input. The default is the character set specified in the LANG environment variable. This option can be used to convert from the specified character set to UTF8, thus overriding the LANG setting. You can also input a specific character set for the bind DN, base DN, and the search filter pattern. The ldapsearch tool converts the input from these arguments before it processes the search request. For example, -i no indicates that the bind DN, base DN, and search filter are provided in Norwegian. This argument only affects the command-line input. A filter file (specified with the -f option) will not be converted by ldapsearch.



Specify the path to a directory containing conversion routines. Use these routines if you wish to specify a sorting language that is not supported by your directory server. See Appendix C, “Directory Internationalization” in the Sun ONE Directory Server Reference Manual.



Specify an attribute to sort entries returned by the search. The sort criteria is alphabetical based on the attribute’s value or reverse alphabetical with the form -attribute. You may give multiple -S options to refine the sorting, for example: -S sn -S givenname. By default, the entries are not sorted. Use the -x option described in Table 3-3 to perform server-side sorting.



Specify the maximum number of entries to return in response to a search request. Regardless of the value specified here, ldapsearch will never return more entries than the number allowed by the directory server’s nsslapd-sizelimit attribute whose default is 2,000 entries. See “nsslapd-sizelimit (Size Limit)” in Chapter 4 of the Sun ONE Directory Server Reference Manual. This limitation does not apply if you bind as the root DN (with -D "cn=directory manager"), in which case this option defaults to 0 (zero) and the size limit attribute is overridden.



Specify that the search retrieve only attribute names, not the attribute values. This option is useful if you just want to determine if an attribute is present for an entry.



Omit the leading "version: 1" line in the LDIF output.



User-friendly DNs: specify that this alternate form of the DN also be included in the output of a search result entry, in addition to the complete form that is always displayed.



Temporary file output: each attribute of each entry in the search results will be written to a separate file in the system’s temporary directory (usually /tmp). The standard output of the tool will include the name of the file instead of the attribute’s value. When using this option, no base-64 encoding is performed on the values, regardless of content.



URL format : when using temporary file output, the standard output of the tool will include the URL of the file instead of the attribute’s value, for example: jpegPhoto:< file:/tmp/ldapsearch-jpegPhoto-YzaOMh. NOTE: This option is valid only with the -t option.



Format the output of search results so that no line breaks are used within individual attribute values.



Used to specify Simple Authentication and Security Layer (SASL) options (mech, realm, authid and authzid). For more information on these options, see “Configuring LDAP Clients to Use Security” in Chapter 11 of the Sun ONE Directory Server Administration Guide.



Format the output of search results so that the given separator is used between attribute names and their values. NOTE: This option may be used only in conjunction with the -o option.



Format the output of search results to print binary values as they are stored in the directory. When used in conjunction with -o, the binary data in the output will not use base-64 encoding.

LDAP Controls Options

The options in Table 3-3 provide advanced search controls for server-side sorting, virtual lists, and persistent searches. This functionality is available only if the server supports the corresponding LDAP controls. These options will also display any additional information that the server sends in response to the control.

Table 3-3  LDAP Controls Options for ldapsearch 






Use with the -S option (in Table 3-2) to specify that search results be sorted on the server rather than by the ldapsearch command running on the client. This is useful if you want to sort according to a matching rule, as with an international search. It is usually faster to sort on the server, if supported, rather than on the client.



Used to perform a search that keeps the connection open and displays results whenever entries matching the scope and filter of the search are added, modified, or removed. For this persistent search, the ldapsearch tool will run indefinitely. Control-C must be typed to stop it. By default, the tool will instruct the server to return entry change controls with the persistent search results. These controls indicate the type of operation that caused the entry to be detected by the search. pattern has the format:


changeType determines which modifications to an entry are detected and displayed in the output; its possible values are add, delete, modify, moddn, or any. changesOnly is an optional boolean value. The default 1 displays changes when they occur. Specify 0, f, or false to display the results of the search before waiting for changes. entryChangeControls is also an optional boolean value. Specify 0, f, or false if you do not want the server to return entry change controls. In this case, you must also specify a value for the changesOnly parameter.



This virtual list view retrieves only a portion of all results, as determined by the index or value of the search target and the number of entries to be returned before and after the target. This option always requires the -S and -x options to specify the sorting order on the server. The pattern has two possible formats:

  • entriesBefore:entriesAfter:value - Specify the search target as the first entry in the sorted results for which the sort attribute is “greater than” or equal to the given value. For example, -S sn -x -G 5:10:johnson will return 16 entries in alphabetical order of the surname attribute: 5 less than johnson, the entry equal to or following johnson, and the 10 subsequent entries.
  • entriesBefore:entriesAfter:index:count - Specify the search target as the index position relative to the estimated count. If the count is 0 (zero), the index is taken as the absolute index of the target entry within the actual number of entries found. An index of 1 will always select the first entry in the sorted list of results. Otherwise, the target index is the first entry in slice of the list represented by the fraction index/count. For example, -G 5:10:2:4 specifies the index closest to the beginning of the second quarter of the entire list. If the search yielded 100 entries, the target index would be 26, and this pattern would return entries 21 through 36. Give an index greater than the count to specify the last search result in the list.

The number of entriesBefore and entriesAfter displayed may be limited by the beginning and end of the virtual list. ldapsearch takes results and displays the control response to give the total count of entries in the virtual list and the actual index of the target entry. Use these values to refine the search with more accurate index and count parameters.

SSL (Secure Socket Layer) Options

The options in Table 3-4 allow you to use LDAPS (LDAP over SSL) to establish a secure connection for the search. These options are valid only when LDAPS has been enabled and configured in your SSL-enabled directory server. For information on certificate-based authentication and creating a certificate database for use with LDAP clients, see Chapter 11, “Implementing Security,” in the Sun ONE Directory Server Administration Guide. See Using Authentication for examples using the SSL options.

Table 3-4  SSL Options for ldapsearch 






Specify the path and filename of the client’s certificate database. This file may be the same as the certificate database for an SSL-enabled version of Netscape™ Communicator, if available; for example: -P /home/uid/.netscape/cert7.db . When using the command on the same host as the directory server, you may use the server’s own certificate database, for example:-P installDir/slapd-serverID/alias/cert7.db. Use the -P option alone to specify server authentication only.



Specify that SSL be used to provide certificate-based client authentication. This option requires the -N and -W options and any other of the SSL options needed to identify the certificate and the key database.



Specify the certificate name to use for certificate-based client authentication, for example: -N "Directory-Cert".



Specify the path to the security module database. For example:


You need to specify this option only if the security module database is in a different directory from the certificate database itself.



Specify the file and path name of the client’s private key database. This option may be omitted if the key database is in the location already given by the -P option.



Specify the password for the client’s key database given in the -K or -P options. This option is required for certificate-based client authentication.

Return Values

The ldapsearch tool is based on the Sun ONE LDAP SDK for C, and its return values are those of the functions it uses, such as ldap_simple_bind_s(), ldap_search_ext(), and ldap_result(). These functions return both client-side and server-side errors and codes. Table 3-5 shows the possible return values when the directory is hosted on Sun ONE Directory Server. Other LDAP servers may send these values under different circumstances or may send different values. They may also send other result codes entirely; for example, custom result codes from a custom plug-in. For further information about result codes, see the Sun ONE LDAP SDK for C Programming Guide.

Table 3-5  Return Values of ldapsearch 

Return Value

Result Code and Explanation

  0 (0x00)

LDAP_SUCCESS: the operation was successful.

  1 (0x01)

LDAP_OPERATIONS_ERROR: sent by Directory Server for general errors encountered by the server when processing the request.

  2 (0x02)

LDAP_PROTOCOL_ERROR: the search request did not comply with the LDAP protocol. Directory Server may send this error code if it could not sort the search results or could not send sorted results.

  3 (0x03)

LDAP_TIMELIMIT_EXCEEDED: sent by Directory Server if the search exceeded the maximum time specified by the -l option.

  4 (0x04)

LDAP_SIZELIMIT_EXCEEDED: sent by Directory Server if the search found more results than the maximum number of results specified by the -z option.

10 (0x0a)

LDAP_REFERRAL: sent by Directory Server if the given base DN is an entry not handled by the current server and if the referral URL identifies a different server to handle the entry.

11 (0x0b)

LDAP_ADMINLIMIT_EXCEEDED: sent by Directory Server if the search found more results than the limit specified by the lookthroughlimit directive in the slapd.conf configuration file. If not specified in the configuration file, the default limit is 5000.

21 (0x15)

LDAP_INVALID_SYNTAX: sent by Directory Server if your substring filter contains no value for comparison.

32 (0x20)

LDAP_NO_SUCH_OBJECT: sent by Directory Server if the given base DN does not exist and if no referral URLs are available.

50 (0x32)

LDAP_INSUFFICIENT_ACCESS: sent by Directory Server if the DN used for authentication does not have permission to read from the directory.

53 (0x35)

LDAP_UNWILLING_TO_PERFORM: sent by Directory Server if the database is read-only.

81 (0x51)

LDAP_SERVER_DOWN: the LDAP server did not receive the request or the connection to the server was lost.

82 (0x52)

LDAP_LOCAL_ERROR: an error occurred when receiving the results from the server.

83 (0x53)

LDAP_ENCODING_ERROR: the request could not be BER-encoded.

84 (0x54)

LDAP_DECODING_ERROR: an error occurred when decoding the BER-encoded results from the server.

85 (0x55)

LDAP_TIMEOUT: the search exceeded the time specified by the -l option.

87 (0x57)

LDAP_FILTER_ERROR: an error occurred when parsing and BER-encoding a search filter specified on the command-line or in a filter file.

89 (0x59)

LDAP_PARAM_ERROR: one of the options or parameters is invalid.

90 (0x5a)

LDAP_NO_MEMORY: memory cannot be allocated as needed.

91 (0x5b)

LDAP_CONNECT_ERROR: the specified hostname or port is invalid.

92 (0x5c)

LDAP_NOT_SUPPORTED: the -V 2 option is needed to access a server that only supports LDAP v2.

Command-Line Examples

The examples in this section demonstrate common uses of the ldapsearch tool to access a directory. All examples assume the following context:

Returning All Entries

Given the context, the following command will return all entries in the directory:

$ ldapsearch -h hostname -b "dc=example,dc=com" -s sub "objectclass=*"

The "objectclass=*" parameter is a search filter that matches any entry in the directory. The scope is set to the full subtree of the base DN (-s sub), and no attribute list is given, so all attributes for all entries will be returned.

Narrowing a Search

To narrow a search, specify a search filter enclosed in quotation marks directly on the command-line. Then, you can ask to receive only those attributes that you need. For example:

$ ldapsearch -h hostname -b "dc=example,dc=com" "cn=babs jensen" mail telephonenumber

In this example, the search will return only the mail and telephonenumber attributes of all entries with a common name (cn) that matches "babs jensen".

Searching the Root DSE Entry

The root DSE is a special entry that contains a list of all the suffixes supported by the local directory server. You can view this entry by performing a search with an empty search base (-b ""). You must also specify a search scope of base and a filter of "objectclass=*", as follows:

$ ldapsearch -h hostname -b "" -s base "objectclass=*"

Searching the Schema Entry

Sun ONE Directory Server stores all directory server schema in the special entry with the DN "cn=schema". This entry contains information on every object class and attribute defined for your directory server. You can examine the contents of this entry as follows:

$ ldapsearch -h hostname -b "cn=schema" -s base "objectclass=*"


To make searching easier, you can set your search base using the LDAP_BASEDN environment variable. Doing this allows you to avoid specifying the search base with the -b option every time you use the ldapsearch tool.


For information on how to set environment variables, see the documentation for your operating environment.

Typically, you set LDAP_BASEDN to your directory’s root suffix value. Because the root suffix is the topmost entry in your directory, all searches will be able to scan the entire directory tree. For example, suppose you have set LDAP_BASEDN to dc=example,dc=com. To search for cn=babs jensen in your directory, use the following command-line:

$ ldapsearch -h hostname "cn=babs jensen"

In this example, the default scope is sub because the -s option was not used to specify a scope other than the base DN.

Using a Filter File

You can store search filters in a file instead of entering them on the command-line. When creating a filter file, specify each search filter on a separate line. The ldapsearch command runs a separate search with each filter in the order in which they appear in the file. This example uses a file named myFilters reproduced in Code Example 3-1.

Code Example 3-1  myFilters Filter File



Assuming the search base is defined by the LDAP_BASEDN environment variable, the following command returns all entries that match either search filter:

$ ldapsearch -h hostname -f myFilters

In the output, ldapsearch first displays all entries with the surname Francis, and then all entries with the given name Richard. The two searches are independent, so an entry that matches both search criteria will be returned twice.

You can limit the set of attributes returned by specifying the attribute names that you want at the end of the search line. For example, the following ldapsearch command performs both searches, but returns only the surname and the given name attributes of each entry:

$ ldapsearch -h hostname -f myFilters sn givenname

Specifying Commas in Filters

When a DN within a search filter contains a comma as part of its value, you must escape the comma with a backslash (\). For example, to find everyone in the “Office Bolivia, S.A.” subtree of the directory, use the following command:

$ ldapsearch -h hostname \
             -b "o=Office Bolivia\, S.A.,dc=example,dc=com" \

Using Authentication

There are two levels of authentication that the directory server may enforce with clients such as the ldapsearch tool: server authentication and client authentication. In server authentication, the server accepts connections only from clients that have a trusted certificate. In the stronger client authentication the client must sign the certificate with a password-protected private key.


In both cases, use the -p option to specify the directory server’s SSL port. All other non-SSL options retain their original meaning and may be used as necessary.

Using Server Authentication

To perform a search with server authentication, use only the -P SSL option [as discussed in SSL (Secure Socket Layer) Options] on the command-line, in addition to other common options.

$ ldapsearch -h hostname -p 636 -b "dc=siroe,dc=com" \
             -D "uid=bjensen,dc=example,dc=com" -w bindPassword \
             -P /home/bjensen/certs/cert.db \

Using Client Authentication

To perform a search with client authentication, you must give all SSL options [as discussed in SSL (Secure Socket Layer) Options] on the command-line, in addition to other common options.

$ ldapsearch -h hostname -p 636 -b "dc=example,dc=com" \
             -Z -P /home/bjensen/security/cert.db -N "bjscert" \
             -K /home/bjensen/security/key.db -W KeyPassword \


Do not use the -D and -w common options with client authentication, as the bind operation will use the authentication credentials specified with -D and -w instead of the certificate credentials desired.

Previous      Contents      Index      Next     

Copyright 2004 Sun Microsystems, Inc. All rights reserved.