matchedvalues.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. #
  3. # demo for matched values control (RFC 3876)
  4. #
  5. # suppose the uid=jsmith LDAP entry has two mail attributes:
  6. #
  7. # dn: uid=jsmith,ou=People,dc=example,dc=com
  8. # (...)
  9. # mail: jsmith@example.com
  10. # mail: jsmith@example.org
  11. #
  12. # Let's say you want to fetch only the example.org email. Without MV,
  13. # you would first fetch all mail attributes and then filter them further
  14. # on the client. With the MV control, the result can be given to the
  15. # client already filtered.
  16. #
  17. # Sample output:
  18. # $ ./matchedvalues.py
  19. # LDAP filter used: (&(objectClass=inetOrgPerson)(mail=*@example.org))
  20. # Requesting 'mail' attribute back
  21. #
  22. # No matched values control:
  23. # dn: uid=jsmith,ou=People,dc=example,dc=com
  24. # mail: jsmith@example.org
  25. # mail: john@example.com
  26. #
  27. # Matched values control: (mail=*@example.org)
  28. # dn: uid=jsmith,ou=People,dc=example,dc=com
  29. # mail: jsmith@example.org
  30. import ldap
  31. from ldap.controls import MatchedValuesControl
  32. def print_result(search_result):
  33. for n in range(len(search_result)):
  34. print "dn: %s" % search_result[n][0]
  35. for attr in search_result[n][1].keys():
  36. for i in range(len(search_result[n][1][attr])):
  37. print "%s: %s" % (attr, search_result[n][1][attr][i])
  38. print
  39. uri = "ldap://ldap.example.com"
  40. base = "dc=example,dc=com"
  41. scope = ldap.SCOPE_SUBTREE
  42. filter = "(&(objectClass=inetOrgPerson)(mail=*@example.org))"
  43. control_filter = "(mail=*@example.org)"
  44. ld = ldap.initialize(uri)
  45. mv = MatchedValuesControl(criticality=True, controlValue=control_filter)
  46. res = ld.search_ext_s(base, scope, filter, attrlist = ['mail'])
  47. print "LDAP filter used: %s" % filter
  48. print "Requesting 'mail' attribute back"
  49. print
  50. print "No matched values control:"
  51. print_result(res)
  52. res = ld.search_ext_s(base, scope, filter, attrlist = ['mail'], serverctrls = [mv])
  53. print "Matched values control: %s" % control_filter
  54. print_result(res)