ldap LDAP library interface module¶
This module provides access to the LDAP (Lightweight Directory Access Protocol) C API implemented in OpenLDAP. It is similar to the C API, with the notable differences that lists are manipulated via Python list operations and errors appear as exceptions.
See also
For more detailed information on the C interface, please see the (expired) draft-ietf-ldapext-ldap-c-api
This documentation is current for the Python LDAP module, version 3.4.3. Source and binaries are available from https://www.python-ldap.org/.
Functions¶
This module defines the following functions:
-
ldap.initialize(uri[, trace_level=0[, trace_file=sys.stdout[, trace_stack_limit=None[, fileno=None]]]]) → LDAPObject object¶ Initializes a new connection object for accessing the given LDAP server, and return an
LDAPObjectused to perform operations on that server.The uri parameter may be a comma- or whitespace-separated list of URIs containing only the schema, the host, and the port fields. Note that when using multiple URIs you cannot determine to which URI your client gets connected.
If fileno parameter is given then the file descriptor will be used to connect to an LDAP server. The fileno must either be a socket file descriptor as
intor a file-like object with a fileno() method that returns a socket file descriptor. The socket file descriptor must already be connected.LDAPObjectdoes not take ownership of the file descriptor. It must be kept open during operations and explicitly closed after theLDAPObjectis unbound. The internal connection type is determined from the URI,TCPforldap:///ldaps://,IPC(AF_UNIX) forldapi://. The parameter is not available on macOS when python-ldap is compiled with system libldap, seeINIT_FD_AVAIL.Note that internally the OpenLDAP function ldap_initialize(3) is called which just initializes the LDAP connection struct in the C API - nothing else. Therefore the first call to an operation method (bind, search etc.) then really opens the connection (lazy connect). Before that nothing is sent on the wire. The error handling in the calling application has to correctly handle this behaviour.
Three 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
0for no logging,1for only logging the method calls with arguments,2for logging the method calls with arguments and the complete results and9for also logging the traceback of method calls.This function is a thin wrapper around instantiating
LDAPObject. Any additional keyword arguments are passed toLDAPObject. It is also fine to instantiate aLDAPObject(or a subclass) directly.The function additionally takes bytes_mode and bytes_strictness keyword arguments, which are deprecated and ignored. See Bytes/text management for details.
See also
RFC 4516 - Lightweight Directory Access Protocol (LDAP): Uniform Resource Locator
New in version 3.3: The fileno argument was added.
Deprecated since version 3.4: bytes_mode and bytes_strictness arguments are deprecated.
-
ldap.get_option(option) → int|string¶ This function returns the value of the global option specified by option.
-
ldap.set_option(option, invalue) → None¶ This function sets the value of the global option specified by option to invalue.
Note
Most global settings do not affect existing
LDAPObjectconnections. Applications should callset_option()before they establish connections withinitialize().
Changed in version 3.1: The deprecated functions ldap.init() and ldap.open() were removed.
Constants¶
The module defines various constants. Note that some constants depend on the build options and which underlying libs were used or even on the version of the libs. So before using those constants the application has to explicitly check whether they are available.
General¶
-
ldap.PORT¶ The assigned TCP port number (389) that LDAP servers listen on.
-
ldap.SASL_AVAIL¶ Integer where a non-zero value indicates that python-ldap was built with support for SASL (Cyrus-SASL).
-
ldap.TLS_AVAIL¶ Integer where a non-zero value indicates that python-ldap was built with support for SSL/TLS (OpenSSL or similar libs).
-
ldap.INIT_FD_AVAIL¶ Integer where a non-zero value indicates that python-ldap supports
initialize()from a file descriptor. The feature is generally available except on macOS when python-ldap is compiled with system libldap.
Options¶
See also
ldap.conf(5) and ldap_get_option(3)
For use with functions set_option() and get_option() and
methods LDAPObject.set_option() and LDAPObject.get_option()
the following option identifiers are defined as constants:
-
ldap.OPT_API_FEATURE_INFO¶
-
ldap.OPT_API_INFO¶
-
ldap.OPT_CLIENT_CONTROLS¶
-
ldap.OPT_DEBUG_LEVEL¶ Sets the debug level within the underlying OpenLDAP C lib (libldap). libldap sends the log messages to stderr.
-
ldap.OPT_DEFBASE¶
-
ldap.OPT_DEREF¶ Specifies how alias dereferencing is done within the underlying LDAP C lib.
-
ldap.OPT_ERROR_STRING¶
-
ldap.OPT_DIAGNOSTIC_MESSAGE¶
-
ldap.OPT_HOST_NAME¶
-
ldap.OPT_MATCHED_DN¶
-
ldap.OPT_NETWORK_TIMEOUT¶ Changed in version 3.0: A timeout of
-1orNoneresets timeout to infinity.
-
ldap.OPT_PROTOCOL_VERSION¶ Sets the LDAP protocol version used for a connection. This is mapped to object attribute ldap.LDAPObject.protocol_version
-
ldap.OPT_REFERRALS¶ int specifying whether referrals should be automatically chased within the underlying LDAP C lib.
-
ldap.OPT_REFHOPLIMIT¶
-
ldap.OPT_RESTART¶
-
ldap.OPT_SERVER_CONTROLS¶
-
ldap.OPT_SIZELIMIT¶
-
ldap.OPT_SUCCESS¶
-
ldap.OPT_TIMELIMIT¶
-
ldap.OPT_TIMEOUT¶ Changed in version 3.0: A timeout of
-1orNoneresets timeout to infinity.
-
ldap.OPT_URI¶
SASL options¶
Unlike most other options, SASL options must be set on an
LDAPObject instance.
-
ldap.OPT_X_SASL_AUTHCID¶
-
ldap.OPT_X_SASL_AUTHZID¶
-
ldap.OPT_X_SASL_MECH¶
-
ldap.OPT_X_SASL_NOCANON¶ If set to zero, SASL host name canonicalization is disabled.
-
ldap.OPT_X_SASL_REALM¶
-
ldap.OPT_X_SASL_SECPROPS¶
-
ldap.OPT_X_SASL_SSF¶
-
ldap.OPT_X_SASL_SSF_EXTERNAL¶
-
ldap.OPT_X_SASL_SSF_MAX¶
-
ldap.OPT_X_SASL_SSF_MIN¶
TLS options¶
Warning
libldap does not materialize all TLS settings immediately. You must use
OPT_X_TLS_NEWCTX with value 0 to instruct libldap to
apply pending TLS settings and create a new internal TLS context:
conn = ldap.initialize("ldap://ldap.example")
conn.set_option(ldap.OPT_X_TLS_CACERTFILE, '/path/to/ca.pem')
conn.set_option(ldap.OPT_X_TLS_NEWCTX, 0)
conn.start_tls_s()
conn.simple_bind_s(dn, password)
-
ldap.OPT_X_TLS_NEWCTX¶ set and apply TLS settings to internal TLS context. Value
0creates a new client-side context.
-
ldap.OPT_X_TLS_PACKAGE¶ Get TLS implementation, known values are
GnuTLSMozNSS(Mozilla NSS)OpenSSL
-
ldap.OPT_X_TLS_CACERTDIR¶ get/set path to directory with CA certs
-
ldap.OPT_X_TLS_CACERTFILE¶ get/set path to PEM file with CA certs
-
ldap.OPT_X_TLS_CERTFILE¶ get/set path to file with PEM encoded cert for client cert authentication, requires
OPT_X_TLS_KEYFILE.
-
ldap.OPT_X_TLS_KEYFILE¶ get/set path to file with PEM encoded key for client cert authentication, requires
OPT_X_TLS_CERTFILE.
-
ldap.OPT_X_TLS_CRLCHECK¶ get/set certificate revocation list (CRL) check mode. CRL validation requires
OPT_X_TLS_CRLFILE.OPT_X_TLS_CRL_NONE- Don’t perform CRL checks
OPT_X_TLS_CRL_PEER- Perform CRL check for peer’s end entity cert.
OPT_X_TLS_CRL_ALL- Perform CRL checks for the whole cert chain
-
ldap.OPT_X_TLS_CRLFILE¶ get/set path to CRL file
-
ldap.OPT_X_TLS_CRL_ALL¶ value for
OPT_X_TLS_CRLCHECK
-
ldap.OPT_X_TLS_CRL_NONE¶ value for
OPT_X_TLS_CRLCHECK
-
ldap.OPT_X_TLS_CRL_PEER¶ value for
OPT_X_TLS_CRLCHECK
-
ldap.OPT_X_TLS_REQUIRE_CERT¶ get/set validation strategy for server cert.
OPT_X_TLS_NEVER- Don’t check server cert and host name
OPT_X_TLS_ALLOW- Used internally by slapd server.
OPT_X_TLS_DEMAND- Validate peer cert chain and host name
OPT_X_TLS_HARD- Same as
OPT_X_TLS_DEMAND
-
ldap.OPT_X_TLS_REQUIRE_SAN¶ get/set how OpenLDAP validates subject alternative name extension, available in OpenLDAP 2.4.52 and newer.
OPT_X_TLS_NEVER- Don’t check SAN
OPT_X_TLS_ALLOW- Check SAN first, always fall back to subject common name (default)
OPT_X_TLS_TRY- Check SAN first, only fall back to subject common name, when no SAN extension is present (RFC 6125 conform validation)
OPT_X_TLS_DEMAND- Validate peer cert chain and host name
OPT_X_TLS_HARD- Require SAN, don’t fall back to subject common name
New in version 3.4.0.
-
ldap.OPT_X_TLS_ALLOW¶ Value for
OPT_X_TLS_REQUIRE_CERTandOPT_X_TLS_REQUIRE_SAN
-
ldap.OPT_X_TLS_DEMAND¶ Value for
OPT_X_TLS_REQUIRE_CERTandOPT_X_TLS_REQUIRE_SAN
-
ldap.OPT_X_TLS_HARD¶ Value for
OPT_X_TLS_REQUIRE_CERTandOPT_X_TLS_REQUIRE_SAN
-
ldap.OPT_X_TLS_NEVER¶ Value for
OPT_X_TLS_REQUIRE_CERTandOPT_X_TLS_REQUIRE_SAN
-
ldap.OPT_X_TLS_TRY¶ Value for
OPT_X_TLS_REQUIRE_CERTDeprecated since version 3.3.0: This value is only used by slapd server internally. It will be removed in the future.
-
ldap.OPT_X_TLS_CIPHER¶ get cipher suite name from TLS session
-
ldap.OPT_X_TLS_CIPHER_SUITE¶ get/set allowed cipher suites
-
ldap.OPT_X_TLS_CTX¶ get address of internal memory address of TLS context (DO NOT USE)
-
ldap.OPT_X_TLS_PEERCERT¶ Get peer’s certificate as binary ASN.1 data structure (DER)
New in version 3.4.1.
Note
The option leaks memory with OpenLDAP < 2.5.8.
-
ldap.OPT_X_TLS_PROTOCOL_MIN¶ get/set minimum protocol version (wire protocol version as int)
-
ldap.OPT_X_TLS_PROTOCOL_MAX¶ get/set maximum protocol version (wire protocol version as int), available in OpenLDAP 2.5 and newer.
New in version 3.4.1.
-
ldap.OPT_X_TLS_PROTOCOL_SSL3¶ Value for
OPT_X_TLS_PROTOCOL_MINandOPT_X_TLS_PROTOCOL_MAX, represents SSL 3New in version 3.4.1.
-
ldap.OPT_X_TLS_PROTOCOL_TLS1_0¶ Value for
OPT_X_TLS_PROTOCOL_MINandOPT_X_TLS_PROTOCOL_MAX, represents TLS 1.0New in version 3.4.1.
-
ldap.OPT_X_TLS_PROTOCOL_TLS1_1¶ Value for
OPT_X_TLS_PROTOCOL_MINandOPT_X_TLS_PROTOCOL_MAX, represents TLS 1.1New in version 3.4.1.
-
ldap.OPT_X_TLS_PROTOCOL_TLS1_2¶ Value for
OPT_X_TLS_PROTOCOL_MINandOPT_X_TLS_PROTOCOL_MAX, represents TLS 1.2New in version 3.4.1.
-
ldap.OPT_X_TLS_PROTOCOL_TLS1_3¶ Value for
OPT_X_TLS_PROTOCOL_MINandOPT_X_TLS_PROTOCOL_MAX, represents TLS 1.3New in version 3.4.1.
-
ldap.OPT_X_TLS_VERSION¶ Get negotiated TLS protocol version as string
-
ldap.OPT_X_TLS_RANDOM_FILE¶ get/set path to /dev/urandom (DO NOT USE)
-
ldap.OPT_X_TLS¶ Deprecated since version 3.3.0: The option is deprecated in OpenLDAP and should no longer be used. It will be removed in the future.
Note
OpenLDAP supports several TLS/SSL libraries. OpenSSL is the most common backend. Some options may not be available when libldap uses NSS, GnuTLS, or Apple’s Secure Transport backend.
DN format flags¶
This constants are used for DN-parsing functions found in
sub-module ldap.dn.
See also
-
ldap.DN_FORMAT_LDAP¶
-
ldap.DN_FORMAT_LDAPV3¶
-
ldap.DN_FORMAT_LDAPV2¶
-
ldap.DN_FORMAT_DCE¶
-
ldap.DN_FORMAT_UFN¶
-
ldap.DN_FORMAT_AD_CANONICAL¶
-
ldap.DN_FORMAT_MASK¶
-
ldap.DN_PRETTY¶
-
ldap.DN_SKIP¶
-
ldap.DN_P_NOLEADTRAILSPACES¶
-
ldap.DN_P_NOSPACEAFTERRDN¶
-
ldap.DN_PEDANTIC¶
Exceptions¶
The module defines the following exceptions:
-
exception
ldap.LDAPError¶ This is the base class of all exceptions 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 with additional information. All fields are optional and more fields may be added in the future. Currently,
python-ldapmay set the following fields:'result': a numeric code of the error class.'desc': string giving a description of the error class, as provided by calling OpenLDAP’sldap_err2stringon theresult.'info': string containing more information that the server may have sent. The value is server-specific: for example, the OpenLDAP server may send different info messages than Active Directory or 389-DS.'matched': truncated form of the name provided or alias. dereferenced for the lowest entry (object or alias) that was matched.'msgid': ID of the matching asynchronous request. This can be used in asynchronous code whereresult()raises the result of an operation as an exception. For example, this is the case forcompare(), always raises the boolean result as an exception (COMPARE_TRUEorCOMPARE_FALSE).'ctrls': list ofldap.controls.LDAPControlinstances attached to the error.'errno': the Cerrno, usually set by system calls orlibcrather than the LDAP libraries.
-
exception
ldap.ADMINLIMIT_EXCEEDED¶
-
exception
ldap.AFFECTS_MULTIPLE_DSAS¶
-
exception
ldap.ALIAS_DEREF_PROBLEM¶ A problem was encountered when dereferencing an alias. (Sets the
matchedfield.)
-
exception
ldap.ALIAS_PROBLEM¶ An alias in the directory points to a nonexistent entry. (Sets the
matchedfield.)
-
exception
ldap.ALREADY_EXISTS¶ The entry already exists. E.g. the dn specified with
add()already exists in the DIT.
-
exception
ldap.AUTH_UNKNOWN¶ The authentication method specified to
bind()is not known.
-
exception
ldap.BUSY¶ The DSA is busy.
-
exception
ldap.CLIENT_LOOP¶
-
exception
ldap.COMPARE_FALSE¶ A compare operation returned false. (This exception should only be seen asynchronous operations, because
compare_s()returns a boolean result.)
-
exception
ldap.COMPARE_TRUE¶ A compare operation returned true. (This exception should only be seen asynchronous operations, because
compare_s()returns a boolean result.)
-
exception
ldap.CONFIDENTIALITY_REQUIRED¶ Indicates that the session is not protected by a protocol such as Transport Layer Security (TLS), which provides session confidentiality.
-
exception
ldap.CONNECT_ERROR¶
-
exception
ldap.CONSTRAINT_VIOLATION¶ An attribute value specified or an operation started violates some server-side constraint (e.g., a postalAddress has too many lines or a line that is too long or a password is expired).
-
exception
ldap.CONTROL_NOT_FOUND¶
-
exception
ldap.DECODING_ERROR¶ An error was encountered decoding a result from the LDAP server.
-
exception
ldap.ENCODING_ERROR¶ An error was encountered encoding parameters to send to the LDAP server.
-
exception
ldap.FILTER_ERROR¶ An invalid filter was supplied to
search()(e.g. unbalanced parentheses).
-
exception
ldap.INAPPROPRIATE_AUTH¶ Inappropriate authentication was specified (e.g.
AUTH_SIMPLEwas specified and the entry does not have a userPassword attribute).
-
exception
ldap.INAPPROPRIATE_MATCHING¶ Filter type not supported for the specified attribute.
-
exception
ldap.INSUFFICIENT_ACCESS¶ The user has insufficient access to perform the operation.
-
exception
ldap.INVALID_CREDENTIALS¶ Invalid credentials were presented during
bind()orsimple_bind(). (e.g., the wrong password).
-
exception
ldap.INVALID_DN_SYNTAX¶ A syntactically invalid DN was specified. (Sets the
matchedfield.)
-
exception
ldap.INVALID_SYNTAX¶ An attribute value specified by the client did not comply to the syntax defined in the server-side schema.
-
exception
ldap.IS_LEAF¶ The object specified is a leaf of the directory tree. Sets the
matchedfield of the exception dictionary value.
-
exception
ldap.LOCAL_ERROR¶ Some local error occurred. This is usually due to failed memory allocation.
-
exception
ldap.LOOP_DETECT¶ A loop was detected.
-
exception
ldap.MORE_RESULTS_TO_RETURN¶
-
exception
ldap.NAMING_VIOLATION¶ A naming violation occurred. This is raised e.g. if the LDAP server has constraints about the tree naming.
-
exception
ldap.NO_OBJECT_CLASS_MODS¶ Modifying the objectClass attribute as requested is not allowed (e.g. modifying structural object class of existing entry).
-
exception
ldap.NOT_ALLOWED_ON_NONLEAF¶ The operation is not allowed on a non-leaf object.
-
exception
ldap.NOT_ALLOWED_ON_RDN¶ The operation is not allowed on an RDN.
-
exception
ldap.NOT_SUPPORTED¶
-
exception
ldap.NO_MEMORY¶
-
exception
ldap.NO_RESULTS_RETURNED¶
-
exception
ldap.NO_SUCH_ATTRIBUTE¶ The attribute type specified does not exist in the entry.
-
exception
ldap.NO_SUCH_OBJECT¶ The specified object does not exist in the directory. Sets the
matchedfield of the exception dictionary value.
-
exception
ldap.OBJECT_CLASS_VIOLATION¶ An object class violation occurred when the LDAP server checked the data sent by the client against the server-side schema (e.g. a “must” attribute was missing in the entry data).
-
exception
ldap.OPERATIONS_ERROR¶ An operations error occurred.
-
exception
ldap.OTHER¶ An unclassified error occurred.
-
exception
ldap.PARAM_ERROR¶ An ldap routine was called with a bad parameter.
-
exception
ldap.PARTIAL_RESULTS¶ Partial results only returned. This exception is raised if a referral is received when using LDAPv2. (This exception should never be seen with LDAPv3.)
-
exception
ldap.PROTOCOL_ERROR¶ A violation of the LDAP protocol was detected.
-
exception
ldap.RESULTS_TOO_LARGE¶ The result does not fit into a UDP packet. This happens only when using UDP-based CLDAP (connection-less LDAP) which is not supported anyway.
-
exception
ldap.SASL_BIND_IN_PROGRESS¶
-
exception
ldap.SERVER_DOWN¶ The LDAP library can’t contact the LDAP server.
-
exception
ldap.SIZELIMIT_EXCEEDED¶ An LDAP size limit was exceeded. This could be due to a
sizelimitconfiguration on the LDAP server.
-
exception
ldap.STRONG_AUTH_NOT_SUPPORTED¶ The LDAP server does not support strong authentication.
-
exception
ldap.STRONG_AUTH_REQUIRED¶ Strong authentication is required for the operation.
-
exception
ldap.TIMELIMIT_EXCEEDED¶ An LDAP time limit was exceeded.
-
exception
ldap.TIMEOUT¶ A timelimit was exceeded while waiting for a result from the server.
-
exception
ldap.TYPE_OR_VALUE_EXISTS¶ An attribute type or attribute value specified already exists in the entry.
-
exception
ldap.UNAVAILABLE¶ The DSA is unavailable.
-
exception
ldap.UNAVAILABLE_CRITICAL_EXTENSION¶ Indicates that the LDAP server was unable to satisfy a request because one or more critical extensions were not available. Either the server does not support the control or the control is not appropriate for the operation type.
-
exception
ldap.UNDEFINED_TYPE¶ An attribute type used is not defined in the server-side schema.
-
exception
ldap.UNWILLING_TO_PERFORM¶ The DSA is unwilling to perform the operation.
-
exception
ldap.USER_CANCELLED¶ The operation was cancelled via the
abandon()method.
The above exceptions are raised when a result code from an underlying API call does not indicate success.
Warnings¶
-
class
ldap.LDAPBytesWarning¶ This warning is deprecated. python-ldap no longer raises it.
It used to be raised under Python 2 when bytes/text mismatch in non-strict bytes mode. See Bytes/text management for details.
New in version 3.0.0.
Changed in version 3.4.0: Deprecated.
LDAPObject classes¶
-
class
ldap.ldapobject.LDAPObject¶ Instances of
LDAPObjectare returned byinitialize(). The connection is automatically unbound and closed when the LDAP object is deleted.LDAPObjectis an alias ofSimpleLDAPObject, the default connection class. If you wish to use a different class, instantiate it directly instead of callinginitialize().(It is also possible, but not recommended, to change the default by setting
ldap.ldapobject.LDAPObjectto a different class.)
-
class
ldap.ldapobject.SimpleLDAPObject(uri, trace_level=0, trace_file=None, trace_stack_limit=5, bytes_mode=None, bytes_strictness=None, fileno=None)¶ This basic class wraps all methods of the underlying C API object.
The arguments are same as for the
initialize()function.
-
class
ldap.ldapobject.ReconnectLDAPObject(uri, trace_level=0, trace_file=None, trace_stack_limit=5, bytes_mode=None, bytes_strictness=None, retry_max=1, retry_delay=60.0, fileno=None)¶ SimpleLDAPObjectsubclass whose synchronous request methods automatically reconnect and re-try in case of server failure (ldap.SERVER_DOWN).The first arguments are same as for the
initialize()function. For automatic reconnects it has additional arguments:- retry_max: specifies the number of reconnect attempts before
re-raising the
ldap.SERVER_DOWNexception. - retry_delay: specifies the time in seconds between reconnect attempts.
This class also implements the pickle protocol.
- retry_max: specifies the number of reconnect attempts before
re-raising the
Arguments for LDAPv3 controls¶
The ldap.controls module can be used for constructing and
decoding LDAPv3 controls. These arguments are available in the methods
with names ending in _ext or _ext_s:
- serverctrls
- is a list of
ldap.controls.LDAPControlinstances sent to the server along with the LDAP request (see moduleldap.controls). These are controls which alter the behaviour of the server when processing the request if the control is supported by the server. The effect of controls might differ depending on the type of LDAP request or controls might not be applicable with certain LDAP requests at all. - clientctrls
- is a list of
ldap.controls.LDAPControlinstances passed to the client API and alter the behaviour of the client when processing the request.
Sending LDAP requests¶
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.
LDAPObject instances have the following methods:
-
LDAPObject.abandon(msgid) → None¶
-
LDAPObject.abandon_ext(msgid[, serverctrls=None[, clientctrls=None]]) → None¶ Abandons an LDAP operation in progress without waiting for a LDAP response. The msgid argument 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 toresult().serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
-
LDAPObject.add(dn, modlist) → int¶
-
LDAPObject.add_s(dn, modlist) → None¶
-
LDAPObject.add_ext(dn, modlist[, serverctrls=None[, clientctrls=None]]) → int¶
-
LDAPObject.add_ext_s(dn, modlist[, serverctrls=None[, clientctrls=None]]) → tuple¶ 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()andadd_ext()return the message ID of the initiated request.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The dn argument, and mod_type (second item) of modlist are text strings; see Bytes/text management.
-
LDAPObject.bind(who, cred, method) → int¶
-
LDAPObject.bind_s(who, cred, method) → None¶
-
LDAPObject.cancel(cancelid[, serverctrls=None[, clientctrls=None]]) → None¶ 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 toabandon()this extended operation gets an result from the server and thus should be preferred if the server supports it.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
RFC 3909 - Lightweight Directory Access Protocol (LDAP): Cancel Operation
-
LDAPObject.compare(dn, attr, value) → int¶
-
LDAPObject.compare_s(dn, attr, value) → bool¶
-
LDAPObject.compare_ext(dn, attr, value[, serverctrls=None[, clientctrls=None]]) → int¶
-
LDAPObject.compare_ext_s(dn, attr, value[, serverctrls=None[, clientctrls=None]]) → bool¶ Perform an LDAP comparison between the attribute named attr of entry dn, and the value value. The synchronous forms returns
TrueorFalse. The asynchronous forms returns the message ID of the initiated request, and the result of the asynchronous compare can be obtained usingresult(). The operation can fail with an exception, e.g.ldap.NO_SUCH_OBJECTwhen dn does not exist orldap.UNDEFINED_TYPEfor an invalid attribute.Note that the asynchronous technique yields the answer by raising the exception objects
ldap.COMPARE_TRUEorldap.COMPARE_FALSE.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The dn and attr arguments are text strings; see Bytes/text management.
-
LDAPObject.delete(dn) → int¶
-
LDAPObject.delete_s(dn) → None¶
-
LDAPObject.delete_ext(dn[, serverctrls=None[, clientctrls=None]]) → int¶
-
LDAPObject.delete_ext_s(dn[, serverctrls=None[, clientctrls=None]]) → tuple¶ Performs an LDAP delete operation on dn. The asynchronous form returns the message id of the initiated request, and the result can be obtained from a subsequent call to
result().serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The dn argument is text string; see Bytes/text management.
-
LDAPObject.extop(extreq[,serverctrls=None[,clientctrls=None]]]) → int¶
-
LDAPObject.extop_s(extreq[,serverctrls=None[,clientctrls=None[,extop_resp_class=None]]]]) -> (respoid,respvalue)¶ Performs an LDAP extended operation. The asynchronous form returns the message id of the initiated request, and the result can be obtained from a subsequent call to
extop_result().The extreq is an instance of class
ldap.extop.ExtendedRequestcontaining the parameters for the extended operation request.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
If argument extop_resp_class is set to a sub-class of
ldap.extop.ExtendedResponsethis class is used to return an object of this class instead of a raw BER value in respvalue.
-
LDAPObject.extop_result(self, msgid=ldap.RES_ANY, all=1, timeout=None) -> (respoid, respvalue)¶ Wrapper method around
result4()just for retrieving the result of an extended operation sent before.
-
LDAPObject.modify(dn, modlist) → int¶
-
LDAPObject.modify_s(dn, modlist) → None¶
-
LDAPObject.modify_ext(dn, modlist[, serverctrls=None[, clientctrls=None]]) → int¶
-
LDAPObject.modify_ext_s(dn, modlist[, serverctrls=None[, clientctrls=None]]) → tuple¶ 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
ldap.MOD_ADD,ldap.MOD_DELETE, orldap.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 beNoneindicating that all attributes are to be deleted.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The asynchronous methods
modify()andmodify_ext()return the message ID of the initiated request.You might want to look into sub-module
ldap.modlistfor generating modlist.The dn argument, and mod_type (second item) of modlist are text strings; see Bytes/text management.
-
LDAPObject.modrdn(dn, newrdn[, delold=1]) → int¶
-
LDAPObject.modrdn_s(dn, newrdn[, delold=1]) → None¶ Perform a
modify RDNoperation, (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()andrename_s()methods since the modrdn2* routines in the C library are deprecated.The dn and newrdn arguments are text strings; see Bytes/text management.
-
LDAPObject.passwd(user, oldpw, newpw[, serverctrls=None[, clientctrls=None]]) → int¶
-
LDAPObject.passwd_s(user, oldpw, newpw [, serverctrls=None [, clientctrls=None] [, extract_newpw=False]]]) -> (respoid, respvalue)¶ Perform a
LDAP Password Modify Extended Operationoperation 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.If oldpw is not
Noneit has to match the old password of the specified user which is sometimes used when a user changes his own password.respoid is always
None. respvalue is alsoNoneunless newpw wasNone. This requests that the server generate a new random password. If extract_newpw isTrue, this password is a bytes object available throughrespvalue.genPasswd, otherwise respvalue is the raw ASN.1 response (this is deprecated and only for backwards compatibility).serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The asynchronous version returns the initiated message id.
The user, oldpw and newpw arguments are text strings; see Bytes/text management.
See also
RFC 3062 - LDAP Password Modify Extended Operation
ldap.extop.passwd
-
LDAPObject.rename(dn, newrdn[, newsuperior=None[, delold=1[, serverctrls=None[, clientctrls=None]]]]) → int¶
-
LDAPObject.rename_s(dn, newrdn[, newsuperior=None[, delold=1[, serverctrls=None[, clientctrls=None]]]]) → None¶ Perform a
Renameoperation, (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 newsuperior is used to specify a new parent DN for moving an entry in the tree (not all LDAP servers support this). The optional parameter delold is used to specify whether the old RDN should be kept as an attribute of the entry or not.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The dn and newdn arguments are text strings; see Bytes/text management.
-
LDAPObject.result([msgid=RES_ANY[, all=1[, timeout=None]]]) → 2-tuple¶ This method is used to wait for and return the result of an operation previously initiated by one of the LDAP asynchronous operations (e.g.
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_ANYand the methodresult2()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_ENTRYandRES_SEARCH_REFERENCE, until the final result which has a result type ofRES_SEARCH_RESULTand 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
0effects a poll. If a timeout does occur, aldap.TIMEOUTexception 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-typeis 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, orRES_COMPARE.If all is
0, one response at a time is returned on each call toresult(), with termination indicated byresult-databeing an empty list.See
search()for a description of the search result’sresult-data, otherwise theresult-datais normally meaningless.
-
LDAPObject.result2([msgid=RES_ANY[, all=1[, timeout=None]]]) → 3-tuple¶ This method behaves almost exactly like
result(). But it returns a 3-tuple also containing the message id of the outstanding LDAP operation a particular result message belongs to. This is especially handy if one needs to dispatch results obtained withmsgid=RES_ANYto several consumer threads which invoked a particular LDAP operation.
-
LDAPObject.result3([msgid=RES_ANY[, all=1[, timeout=None]]]) → 4-tuple¶ This method behaves almost exactly like
result2(). But it returns an extra item in the tuple, the decoded server controls.
-
LDAPObject.result4([msgid=RES_ANY[, all=1[, timeout=None[, add_ctrls=0[, add_intermediates=0[, add_extop=0[, resp_ctrl_classes=None]]]]]]]) → 6-tuple¶ This method behaves almost exactly like
result3(). But it returns an extra items in the tuple, the decoded results of an extended response.The additional arguments are:
add_ctrls (integer flag) specifies whether response controls are returned.
add_intermediates (integer flag) specifies whether response controls of intermediate search results are returned.
add_extop (integer flag) specifies whether the response of an extended operation is returned. If using extended operations you should consider using the method
extop_result()orextop_s()instead.resp_ctrl_classes is a dictionary mapping the OID of a response controls to a
ldap.controls.ResponseControlclass of response controls known by the application. So the response control value will be automatically decoded. IfNonethe global dictionaryldap.controls.KNOWN_RESPONSE_CONTROLSis used instead.
-
LDAPObject.sasl_interactive_bind_s(who, auth[, serverctrls=None[, clientctrls=None[, sasl_flags=ldap.SASL_QUIET]]]) → None¶ This call is used to bind to the directory with a SASL bind request.
auth is an
ldap.sasl.sasl()instance.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
-
LDAPObject.sasl_non_interactive_bind_s(sasl_mech[, serverctrls=None[, clientctrls=None[, sasl_flags=ldap.SASL_QUIET[, authz_id='']]]]) → None¶ This call is used to bind to the directory with a SASL bind request with non-interactive SASL mechanism defined with argument sasl_mech and internally calls
sasl_interactive_bind_s().serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
-
LDAPObject.sasl_external_bind_s([serverctrls=None[, clientctrls=None[, sasl_flags=ldap.SASL_QUIET[, authz_id='']]]]) → None¶ This call is used to bind to the directory with a SASL bind request with mechanism EXTERNAL and internally calls
sasl_non_interactive_bind_s().serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
-
LDAPObject.sasl_gssapi_bind_s([serverctrls=None[, clientctrls=None[, sasl_flags=ldap.SASL_QUIET[, authz_id='']]]]) → None¶ This call is used to bind to the directory with a SASL bind request with mechanism GSSAPI and internally calls
sasl_non_interactive_bind_s().serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
-
LDAPObject.simple_bind([who=None[, cred=None[, serverctrls=None[, clientctrls=None]]]]) → int¶
-
LDAPObject.simple_bind_s([who=None[, cred=None[, serverctrls=None[, clientctrls=None]]]]) → None¶ 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 beAUTH_SIMPLE.serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
The who and cred arguments are text strings; see Bytes/text management.
Changed in version 3.0:
simple_bind()andsimple_bind_s()now acceptNonefor who and cred, too.
-
LDAPObject.search(base, scope[, filterstr='(objectClass=*)'[, attrlist=None[, attrsonly=0]]]) → int¶
-
LDAPObject.search_s(base, scope[, filterstr='(objectClass=*)'[, attrlist=None[, attrsonly=0]]]) → list|None¶
-
LDAPObject.search_st(base, scope[, filterstr='(objectClass=*)'[, attrlist=None[, attrsonly=0[, timeout=-1]]]]) → list|None¶
-
LDAPObject.search_ext(base, scope[, filterstr='(objectClass=*)'[, attrlist=None[, attrsonly=0[, serverctrls=None[, clientctrls=None[, timeout=-1[, sizelimit=0]]]]]]]) → int¶
-
LDAPObject.search_ext_s(base, scope[, filterstr='(objectClass=*)'[, attrlist=None[, attrsonly=0[, serverctrls=None[, clientctrls=None[, timeout=-1[, sizelimit=0]]]]]]]) → list|None¶ 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), orSCOPE_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 and clientctrls like described in section Arguments for LDAPv3 controls.
The synchronous form with timeout,
search_st()orsearch_ext_s(), will block for at most timeout seconds (or indefinitely if timeout is negative). Aldap.TIMEOUTexception 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()orsearch_ext_s()(client-side search limit). If non-zero not more than sizelimit results are returned by the server.The base and filterstr arguments, and attrlist contents, are text strings; see Bytes/text management.
Changed in version 3.0:
filterstr=Noneis equivalent tofilterstr='(objectClass=*)'.
-
LDAPObject.start_tls_s() → None¶ - Negotiate TLS with server. The
versionattribute must have been set toVERSION3(which it is by default) before calling this method. If TLS could not be started an exception will be raised.See also
RFC 2830 - Lightweight Directory Access Protocol (v3): Extension for Transport Layer Security
-
LDAPObject.unbind() → int¶
-
LDAPObject.unbind_s() → None¶
-
LDAPObject.unbind_ext([serverctrls=None[, clientctrls=None]]) → int¶
-
LDAPObject.unbind_ext_s([serverctrls=None[, clientctrls=None]]) → None¶ 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.
serverctrls and clientctrls like described in section Arguments for LDAPv3 controls.
These methods are all synchronous in nature.
Connection-specific LDAP options¶
-
LDAPObject.get_option(option) → int|string¶ This method returns the value of the LDAPObject option specified by option.
-
LDAPObject.set_option(option, invalue) → None¶ This method sets the value of the LDAPObject option specified by option to invalue.
Object attributes¶
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.
-
LDAPObject.deref -> int Controls whether aliases are automatically dereferenced. This must be one of
DEREF_NEVER,DEREF_SEARCHING,DEREF_FINDINGorDEREF_ALWAYS. This option is mapped to option constantOPT_DEREFand used in the underlying OpenLDAP client lib.
-
LDAPObject.network_timeout -> int Limit on waiting for a network response, in seconds. Defaults to
NO_LIMIT. This option is mapped to option constantOPT_NETWORK_TIMEOUTand used in the underlying OpenLDAP client lib.Changed in version 3.0.0: A timeout of
-1orNoneresets timeout to infinity.
-
LDAPObject.protocol_version -> int Version of LDAP in use (either
VERSION2for LDAPv2 orVERSION3for LDAPv3). This option is mapped to option constantOPT_PROTOCOL_VERSIONand used in the underlying OpenLDAP client lib.Note
It is highly recommended to set the protocol version after establishing a LDAP connection with
ldap.initialize()and before submitting the first request.
-
LDAPObject.sizelimit -> int Limit on size of message to receive from server. Defaults to
NO_LIMIT. This option is mapped to option constantOPT_SIZELIMITand used in the underlying OpenLDAP client lib. Its use is deprecated in favour of sizelimit parameter when usingsearch_ext().
-
LDAPObject.timelimit -> int Limit on waiting for any response, in seconds. Defaults to
NO_LIMIT. This option is mapped to option constantOPT_TIMELIMITand used in the underlying OpenLDAP client lib. Its use is deprecated in favour of usingtimeout.
-
LDAPObject.timeout -> int Limit on waiting for any response, in seconds. Defaults to
NO_LIMIT. This option is used in the wrapper module.
Example¶
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)