Python API

This is the page for ezldap’s Python API documentation. For general-purpose recipes and use cases, check out the Python recipes.

Connection

ezldap.ping(uri)

Returns true if an LDAP server is responding at a given URI by attempting an anonymous bind.

ezldap.supports_starttls(uri)

Determine if the server actually supports StartTLS (both the server software itself supports it, and the server instance itself has been configured with SSL support).

ezldap.auto_bind(conf=None, server_info=True)

Automatically detects LDAP config values and returns a directory binding.

ezldap.dn_address(dn)

Get the “.”-delmited address for a DN (typically a directory naming context/ base dn). If the directory naming context was dc=ezldap,dc=io, then the address would be “ezldap.io”. Typically used when generating fully-qualified hostnames for new hosts (for instance, “hostname.ezldap.io”). However, this function will create addresses for any DN, if so desired.

ezldap.clean_uri(uri)

ldap3 really struggles with URIs ending in a slash. This function cleans common LDAP URI formats to something the underlying ldap3 API can understand.

class ezldap.Connection(host, user=None, password=None, conf=None, authentication='SIMPLE', server_info=True, client_strategy='SYNC', sasl_mechanism=None, sasl_credentials=None)

An object-oriented wrapper around an LDAP connection. To automatically create a binding use ezldap.auto_bind() instead. If either user or password are omitted, the bind is anonymous. conf is a dictionary with any placeholders or key/value combinations that you wish to be passed to ldif templates or details like user/group OUs. When used with the “with” keyword, the connection will automatically call Connection.unbind() (and unbind from the directory) when done.

__init__(host, user=None, password=None, conf=None, authentication='SIMPLE', server_info=True, client_strategy='SYNC', sasl_mechanism=None, sasl_credentials=None)
Parameters:
  • host – An LDAP server URI (eg. ldaps://someserver:636)
  • user – Bind user. If None, bind will be anonymous.
  • password – Bind password. If None, the bind will be anonymous.
  • conf – A dict of configuration falues, such as those generated by ezldap.config().
  • client_strategy – Communication strategy used by the client (defaults to SYNC).
  • authentication – Type of authentication to use, by default ldap3.SIMPLE
  • sasl_mechanism – The SASL mechanism to use for AUTH_SASL authentication. Available mechanisms are EXTERNAL, DIGEST-MD5 (deprecated by RFCs because insecure) and GSSAPI.
  • sasl_credentials – An object specific to the SASL mechanism chosen. Refer to the documentation for each SASL mechanism supported.
  • server_info – Whether to fetch information about the server like schema and supported controls. Setting this to False will significantly increase speed of the bind.
Returns:

Returns a directory binding used to perform operations on a directory.

abandon(message_id, controls=None)

Abandon the operation indicated by message_id

add(dn, object_class=None, attributes=None, controls=None)

Add dn to the DIT, object_class is None, a class name or a list of class names.

Attributes is a dictionary in the form ‘attr’: ‘val’ or ‘attr’: [‘val1’, ‘val2’, …] for multivalued attributes

add_group(groupname, ldif_path='~/.ezldap/add_group.ldif', **kwargs)

Adds a group from an LDIF template.

add_host(hostname, ip_address, ldif_path='~/.ezldap/add_host.ldif', **kwargs)

Add a host to a directory. Hostname is the short hostname (hostname -s), to add. If specifying the fully qualified hostname is desired (or the fully qualified hostname does not match the directory suffix), specify the fully-qualified hostname as “hostname_fq”.

add_to_group(username, groupname, ldif_path='~/.ezldap/add_to_group.ldif', **kwargs)

Adds a user to a group. The user and group in question must already exist.

add_user(username, groupname, password, ldif_path='~/.ezldap/add_user.ldif', **kwargs)

Adds a user. Does not create or modify groups. “groupname” may be None if “gid” is specified.

base_dn()

Detect the base DN/naming context from an LDAP connection.

bind(read_server_info=True, controls=None)

Bind to ldap Server with the authentication method and the user defined in the connection

Parameters:
  • read_server_info – reads info from server
  • controls (list of tuple) – LDAP controls to send along with the bind operation
Returns:

bool

compare(dn, attribute, value, controls=None)

Perform a compare operation

delete(dn, controls=None)

Delete the entry identified by the DN from the DIB.

exists(dn)

Returns true if a given DN exists in an LDAP directory.

extended(request_name, request_value=None, controls=None, no_encode=None)

Performs an extended operation

get_group(group, basedn=None, index='cn')

Return a given group. Searches entire directory if no base search dn given.

get_host(host, basedn=None, index='cn')

Return a given host. Searches entire directory if no base search dn given.

get_user(user, basedn=None, index='uid')

Return given user as a dict or None if none is found. Searches entire directory if no base search dn given.

ldif_add(ldif)

Perform an add operation using an LDIF object.

ldif_modify(ldif)

Perform an LDIF modify operation from an LDIF object.

modify(dn, changes, controls=None)

Modify attributes of entry

  • changes is a dictionary in the form {‘attribute1’: change), ‘attribute2’: [change, change, …], …}
  • change is (operation, [value1, value2, …])
  • operation is 0 (MODIFY_ADD), 1 (MODIFY_DELETE), 2 (MODIFY_REPLACE), 3 (MODIFY_INCREMENT)
modify_add(dn, attrib, value)

Add a single attribute to an object.

modify_delete(dn, attrib, value=None)

Delete a single attribute from an object. If value is None, deletes all attributes of that name.

modify_dn(dn, relative_dn, delete_old_dn=True, new_superior=None, controls=None)

Modify DN of the entry or performs a move of the entry in the DIT.

modify_replace(dn, attrib, value, replace_with=None)

Change a single attribute on an object.

next_gidn(search_filter='(objectClass=posixGroup)', search_base=None, gid_start=10000, gid_attribute='gidNumber')

Determine the next available gid number in a directory tree.

next_uidn(search_filter='(objectClass=posixAccount)', search_base=None, uid_start=10000, uid_attribute='uidNumber')

Determine the next available uid number in a directory tree.

search(search_base, search_filter, search_scope='SUBTREE', dereference_aliases='ALWAYS', attributes=None, size_limit=0, time_limit=0, types_only=False, get_operational_attributes=False, controls=None, paged_size=None, paged_criticality=False, paged_cookie=None, auto_escape=None)

Perform an ldap search:

  • If attributes is empty noRFC2696 with the specified size
  • If paged is 0 and cookie is present the search is abandoned on server attribute is returned
  • If attributes is ALL_ATTRIBUTES all attributes are returned
  • If paged_size is an int greater than 0 a simple paged search is tried as described in
  • Cookie is an opaque string received in the last paged search and must be used on the next paged search response
  • If lazy == True open and bind will be deferred until another LDAP operation is performed
  • If mssing_attributes == True then an attribute not returned by the server is set to None
  • If auto_escape is set it overrides the Connection auto_escape
search_df(search_filter='(objectClass=*)', attributes='*', search_base=None, **kwargs)

A convenience function to search an LDAP directory and return a Pandas DataFrame. Very useful for analyzing the contents of your directory, computing stats, etc. Requires the pandas package to be installed.

search_list(search_filter='(objectClass=*)', attributes='*', search_base=None, **kwargs)

A wrapper around search() with better defaults and output format. A list of dictionaries will be returned, with one dict per output object. If search_base is None, the directory base DN will be used.

Parameters:
  • search_filter – An LDAP search filter.
  • attributes – Attributes to return. If not specified, all defaults will be returned. None will return no attributes.
  • search_base – Level of directory to begin search at, for example ou=People.
Returns:

A list of dicts, one per entry returned.

search_list_t(search_filter='(objectClass=*)', attributes='*', search_base=None, unpack_lists=True, unpack_delimiter='|', **kwargs)

A utility function that returns the transposed result of search_list() (a dict of lists, with one list per attribute.) This is very useful for tasks like retrieving all uidNumbers currently assigned or emails used by users. The DN of each entry is always output.

stream

Used by the LDIFProducer strategy to accumulate the ldif-change operations with a single LDIF header :return: reference to the response stream if defined in the strategy.

unbind(controls=None)

Unbind the connected user. Unbind implies closing session as per RFC4511 (4.3)

Parameters:controls – LDAP controls to send along with the bind operation
usage

Usage statistics for the connection. :return: Usage object

who_am_i()

Return the DN of the user you have currently connected as.

LDIF parser and utilities

ezldap.ldif_read(path, replacements=None)

Read an LDIF file into a list of dicts appropriate for use with ezldap.

Parameters:
  • path – Path of an LDIF file to read.
  • replacements – A dictionary of replacement values to replace $placeholders in the LDIF template.
ezldap.ldif_write(entries, path)

Write self.entries as LDIF file.

Parameters:
  • entries – A list of dicts, such as that returned by Connection.search_list()
  • path – File to write.
ezldap.ldif_print(entries)

Print an LDIF entry to stdout.

Parameters:entries – A list of dicts, such as that returned by Connection.search_list().
ezldap.template(path, replacements=None)

Read a file and substitute replacment entries for placeholders designated by $placeholder_name. If replacements is None, it simply opens and reads a file into a string.

Password utilities

ezldap.random_passwd(length=10, ambiguous_chars=False)

Generate a readable, random password with no ambiguous characters (unless you set that option to true, of course).

ezldap.ssha_passwd(str_val)

Hash and salt a string using SHA1 algorithm and format for use with LDAP.

ezldap.ssha_check(ssha_val, str_val)

Check that a password decodes to the correct password.

ezldap.ssha(val, salt)

Generate an SSHA hash.