Platforms: UNIX,Windows
This module provides access to the LDAP (Lightweight Directory Access Protocol) C API implemented in OpenLDAP 2.3 or newer. It is similar to the C API, with the notable differences that lists are manipulated via Python list operations and errors appear as exceptions. For far more detailed information on the C interface, please see the (expired) draft-ietf-ldapext-ldap-c-api-04. This documentation is current for the Python LDAP module, version 2.3.7.0. Source and binaries are available from http://python-ldap.sourceforge.net/.
The ldap module defines the following functions:
Opens a new connection with an LDAP server, and return an LDAP object (see LDAPObject class) used to perform operations on that server. Parameter uri has to be a valid LDAP URL. The optional arguments are for generating debug log information: trace_level specifies the amount of information being logged, trace_file specifies a file-like object as target of the debug log and trace_stack_limit specifies the stack limit of tracebacks in debug log. Possible values for trace_level are 0 for no logging, 1 for only logging the method calls with arguments, 2 for logging the method calls with arguments and the complete results and 3 for also logging the traceback of method calls.
See also
RFC 4516 - Lightweight Directory Access Protocol (LDAP): Uniform Resource Locator
The module defines various constants.
See also
ldap.conf{5} and ldap_get_options{3}
For use with functions and method set_option() and get_option() the following option identifiers are defined as constants:
This constants are used for DN-parsing functions found in sub-module ldap.dn.
See also
ldap_str2dn{3}
The module defines the following exceptions:
This is the base class of all execeptions raised by the module ldap. Unlike the C interface, errors are not returned as result codes, but are instead turned into exceptions, raised as soon an the error condition is detected.
The exceptions are accompanied by a dictionary possibly containing an string value for the key desc (giving an English description of the error class) and/or a string value for the key info (giving a string containing more information that the server may have sent).
A third possible field of this dictionary is matched and is set to a truncated form of the name provided or alias dereferenced for the lowest entry (object or alias) that was matched.
The above exceptions are raised when a result code from an underlying API call does not indicate success.
Instances of ldap.LDAPObject are returned by initialize() and open() (deprecated). The connection is automatically unbound and closed when the LDAP object is deleted.
Most methods on LDAP objects initiate an asynchronous request to the LDAP server and return a message id that can be used later to retrieve the result with result().
Methods with names ending in _s are the synchronous form and wait for and return with the server’s result, or with None if no data is expected.
The ldap.controls module can be used for constructing and decoding LDAPv3 controls.
LDAPObject instances have the following methods:
Performs an LDAP add operation. The dn argument is the distinguished name (DN) of the entry to add, and modlist is a list of attributes to be added. The modlist is similar the one passed to modify(), except that the operation integer is omitted from the tuples in modlist. You might want to look into sub-module refmodule{ldap.modlist} for generating the modlist.
The asynchronous methods add() and add_ext() return the message ID of the initiated request.
After an LDAP object is created, and before any other operations can be attempted over the connection, a bind operation must be performed.
This method attempts to bind with the LDAP server using either simple authentication, or Kerberos (if available). The first and most general method, bind(), takes a third parameter, method which can currently solely be AUTH_SIMPLE.
Send cancels extended operation for an LDAP operation specified by cancelid. The cancelid should be the message id of an outstanding LDAP operation as returned by the asynchronous methods search(), modify() etc. The caller can expect that the result of an abandoned operation will not be returned from a future call to result(). In opposite to abandon() this extended operation gets an result from the server and thus should be preferred if the server supports it.
RFC 3909 - Lightweight Directory Access Protocol (LDAP): Cancel Operation
Perform an LDAP comparison between the attribute named attr of entry dn, and the value value. The synchronous forms returns 0 for false, or 1 for true. The asynchronous forms returns the message ID of the initiated request, and the result of the asynchronous compare can be obtained using result().
Note that the asynchronous technique yields the answer by raising the exception objects ldap.COMPARE_TRUE or ldap.COMPARE_FALSE.
Note
A design fault in the LDAP API prevents value from containing nul characters.
Performs an LDAP modify operation on an entry’s attributes. The dn argument is the distinguished name (DN) of the entry to modify, and modlist is a list of modifications to make to that entry.
Each element in the list modlist should be a tuple of the form (mod_op,mod_type,mod_vals), where mod_op indicates the operation (one of MOD_ADD, MOD_DELETE, or MOD_REPLACE), mod_type is a string indicating the attribute type name, and mod_vals is either a string value or a list of string values to add, delete or replace respectively. For the delete operation, mod_vals may be None indicating that all attributes are to be deleted.
The asynchronous methods modify() and modify_ext() return the message ID of the initiated request.
You might want to look into sub-module ldap.modlist for generating modlist.
Perform a modify RDN operation, (i.e. a renaming operation). These routines take dn (the DN of the entry whose RDN is to be changed, and newrdn, the new RDN to give to the entry. The optional parameter delold is used to specify whether the old RDN should be kept as an attribute of the entry or not. The asynchronous version returns the initiated message id.
This operation is emulated by rename() and rename_s() methods since the modrdn2* routines in the C library are deprecated.
Perform a LDAP Password Modify Extended Operation operation on the entry specified by user. The old password in oldpw is replaced with the new password in newpw by a LDAP server supporting this operation.
The asynchronous version returns the initiated message id.
See also
RFC 3062 - LDAP Password Modify Extended Operation
This method is used to wait for and return the result of an operation previously initiated by one of the LDAP asynchronous operations (eg search(), modify(), etc.)
The msgid parameter is the integer identifier returned by that method. The identifier is guaranteed to be unique across an LDAP session, and tells the result() method to request the result of that specific operation.
If a result is desired from any one of the in-progress operations, msgid should be specified as the constant RES_ANY and the method result2() should be used instead.
The all parameter only has meaning for search() responses and is used to select whether a single entry of the search response should be returned, or to wait for all the results of the search before returning.
A search response is made up of zero or more search entries followed by a search result. If all is 0, search entries will be returned one at a time as they come in, via separate calls to result(). If all is 1, the search response will be returned in its entirety, i.e. after all entries and the final search result have been received.
For all set to 0, result tuples trickle in (with the same message id), and with the result types RES_SEARCH_ENTRY and RES_SEARCH_REFERENCE, until the final result which has a result type of RES_SEARCH_RESULT and a (usually) empty data field. When all is set to 1, only one result is returned, with a result type of RES_SEARCH_RESULT, and all the result tuples listed in the data field.
The timeout parameter is a limit on the number of seconds that the method will wait for a response from the server. If timeout is negative (which is the default), the method will wait indefinitely for a response. The timeout can be expressed as a floating-point value, and a value of 0 effects a poll. If a timeout does occur, a ldap.TIMEOUT exception is raised, unless polling, in which case (None, None) is returned.
The result() method returns a tuple of the form (result-type, result-data). The first element, result-type is a string, being one of these module constants: RES_BIND, RES_SEARCH_ENTRY, RES_SEARCH_REFERENCE, RES_SEARCH_RESULT, RES_MODIFY, RES_ADD, RES_DELETE, RES_MODRDN, or RES_COMPARE.
If all is 0, one response at a time is returned on each call to result(), with termination indicated by result-data being an empty list.
See search() for a description of the search result’s result-data, otherwise the result-data is normally meaningless.
Perform an LDAP search operation, with base as the DN of the entry at which to start the search, scope being one of SCOPE_BASE (to search the object itself), SCOPE_ONELEVEL (to search the object’s immediate children), or SCOPE_SUBTREE (to search the object and all its descendants).
The filterstr argument is a string representation of the filter to apply in the search.
See also
RFC 4515 - Lightweight Directory Access Protocol (LDAP): String Representation of Search Filters.
Each result tuple is of the form (dn, attrs), where dn is a string containing the DN (distinguished name) of the entry, and attrs is a dictionary containing the attributes associated with the entry. The keys of attrs are strings, and the associated values are lists of strings.
The DN in dn is automatically extracted using the underlying libldap function ldap_get_dn(), which may raise an exception if the DN is malformed.
If attrsonly is non-zero, the values of attrs will be meaningless (they are not transmitted in the result).
The retrieved attributes can be limited with the attrlist parameter. If attrlist is None, all the attributes of each entry are returned.
serverctrls not implemented yet.
clientctrls not implemented yet.
The synchronous form with timeout, search_st() or search_ext_s(), will block for at most timeout seconds (or indefinitely if timeout is negative). A ldap.TIMEOUT exception is raised if no result is received within the specified time.
The amount of search results retrieved can be limited with the sizelimit parameter when using search_ext() or search_ext_s() (client-side search limit). If non-zero not more than sizelimit results are returned by the server.
See also
RFC 2830 - Lightweight Directory Access Protocol (v3): Extension for Transport Layer Security
This call is used to unbind from the directory, terminate the current association, and free resources. Once called, the connection to the LDAP server is closed and the LDAP object is marked invalid. Further invocation of methods on the object will yield exceptions.
These methods are all synchronous in nature.
This synchronous method implements the LDAP “Who Am I?” extended operation.
It is useful for finding out to find out which identity is assumed by the LDAP server after a SASL bind.
See also
RFC 4532 - Lightweight Directory Access Protocol (LDAP) “Who am I?” Operation
Enables or disables manageDSAit mode according to the specified integer flag enable. The integer flag critical specifies if the use of this extended control is marked critical.
See also
Note
This method is somewhat immature and might vanish in future versions if full support for extended controls will be implemented. You have been warned!
If the underlying library provides enough information, each LDAP object will also have the following attributes. These attributes are mutable unless described as read-only.
Version of LDAP in use (either VERSION2 for LDAPv2 or VERSION3 for LDAPv3). This option is mapped to option constant OPT_PROTOCOL_VERSION and used in the underlying OpenLDAP lib.
Note
It is highly recommended to set the protocol version after establishing a LDAP connection with initialize() and before submitting the first request.
The following example demonstrates how to open a connection to an LDAP server using the ldap module and invoke a synchronous subtree search.
>>> import ldap
>>> l = ldap.initialize('ldap://localhost:1390')
>>> l.search_s('ou=Testing,dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(cn=fred*)',['cn','mail'])
[('cn=Fred Feuerstein,ou=Testing,dc=stroeder,dc=de', {'cn': ['Fred Feuerstein']})]
>>> r = l.search_s('ou=Testing,dc=stroeder,dc=de',ldap.SCOPE_SUBTREE,'(objectClass=*)',['cn','mail'])
>>> for dn,entry in r:
>>> print 'Processing',repr(dn)
>>> handle_ldap_entry(entry)