How to connect a query AD with python

Note - this is adapted from a letter and hasn't even been compiled, let alone tested. Though the conepts are pretty straightforward

  • Connect and start TLS
  • Bind with your service principal
  • Bind with the user
  • Close - or rebind to do additional work.

.. I suspect you will want to connect initially like this, start TLS, then bind. It's possible you'll want our cert, but usually you can ignore the fact that you don't trust OU's Cert Authority. Let me know and I can supply it.

dn = "CN=jjjjj,OU=Service Accounts,OU=jjT,OU=jj,DC=jj,DC=edu"
pw = "SomePass"
con = ldap.initialize('ldap://')
con.simple_bind_s( dn, pw )

Next you'll want to bind as the user to test their password. It works best if you construct the DN by adding the base_dn something like follows

student_dn = "CN=" + studentName + 'ou=jjjj,dc=jjj,dc=edu'
con.simple_bind_s( student_dn, student_pw )

Then you'll want to rebind as the service account (assuming you need additional data to validate the user, and that such data is probably needs elevated access) and limit your search query a much as possible.

con.simple_bind_s( dn, pw )
base_dn = 'ou=jjjj,dc=jjjj,dc=edu'
searchScope = ldap.SCOPE_BASE
filter = "cn=studentName"
attrs = ['kkkkk']
ldap_result_id =, searchScope, filter, attrs)