Finding entries in LDAP

To find entries in the ldap directory, you must use the search operation. This operation has a number of parameters, but only two of them are mandatory:

conn.search(search_base,search_filter, attributes)

The following are the parameters:

  • search_base: The location in the ldap directory where the search will start
  • search_filter: A string that describes what you are searching for
  • attributes: Attributes to extract

In this script, we are going to search all users in the FreeIPA demo LDAP server. You can find the following code in the entries_ldap_server.py file:

#!/usr/bin/env python3

from ldap3 import Server, Connection, ObjectDef, AttrDef, Reader, Writer, ALL

LDAP_SERVER ="ipa.demo1.freeipa.org"
LDAP_USER ="uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org"
LDAP_PASSWORD ="Secret123"
LDAP_FILTER = '(objectclass=person)'
LDAP_ATTRS = ["cn", "dn", "sn", "givenName"]

def main():
# Create the Server object with the given address.
server = Server(LDAP_SERVER, get_info=ALL)
#Create a connection object, and bind with the given DN and password.
try:
conn = Connection(server, LDAP_USER, LDAP_PASSWORD, auto_bind=True)
print('LDAP Bind Successful.')
# Perform a search for a pre-defined criteria.
# Mention the search filter / filter type and attributes.
conn.search('dc=demo1,dc=freeipa,dc=org', LDAP_FILTER , attributes=LDAP_ATTRS)
# Print the resulting entries.
for entry in conn.entries:
print(entry)
except core.exceptions.LDAPBindError as e:
# If the LDAP bind failed for reasons such as authentication failure.
print('LDAP Bind Failed: ', e)

if __name__ == '__main__':
main()

This is the execution of the previous script. Here, you request all the entries of person class , starting from the dc=demo1dc=freeipa, and dc=org contexts with the default subtree scope:

[DN: uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org
, DN: uid=manager,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org
, DN: uid=employee,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org
, DN: uid=helpdesk,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org
]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset