Skip to content

Instantly share code, notes, and snippets.

@jclosure
Created September 26, 2015 02:54
Show Gist options
  • Save jclosure/62d14269d5be02c13c0d to your computer and use it in GitHub Desktop.
Save jclosure/62d14269d5be02c13c0d to your computer and use it in GitHub Desktop.
query ldap with python - ipython debugging from repl or cli
#!/usr/local/bin/python
# coding: utf-8
# for windows get ldap module here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap
# python_ldap‑2.4.21‑cp27‑none‑win_amd64.whl
## debugging in ipython: https://github.com/gotcha/ipdb
# debug in in ipython repl with: run -d 'test_ldap2.py' or %run ...
# debug it in ipython repl with: ipdb.runcall(run_filter, Server, DN, Secret, un)
# debug from cli with:
# easy_install ipdb
# python -m ipdb test_ldap2.py
# “import pdb” or “import ipdb as pdb“, then “pdb.set_trace() where you want to have it break in advance“
# b (make breakpoint on line # while in the debugger already)
# n (next)
# ENTER (repeat previous)
# q (quit)
# p <variable> (print value)
# c (continue)
# l (list where you are)
# s (step into subroutine)
# r (continue till the end of the subroutine)
# ! <python command>
import sys
import ldap
Server = "ldap://dc1.mydomain.com:389"
# DN, Secret, un = sys.argv[1:4]
DN, Secret, un = ["[email protected]","mypassword","myusername"]
def run_filter(Server, DN, Secret, un):
Base = "dc=amd,dc=com"
Scope = ldap.SCOPE_SUBTREE
Filter = "(&(objectClass=user)(sAMAccountName="+un+"))"
Attrs = ["displayName","samAccountName"]
try:
l = ldap.initialize(Server)
l.set_option(ldap.OPT_REFERRALS, 0)
l.protocol_version = 3
print l.simple_bind_s(DN, Secret)
r = l.search(Base, Scope, Filter, Attrs)
Type,user = l.result(r,60)
# ipdb.set_trace()
Name,Attrs = user[0]
if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'):
displayName = Attrs['displayName'][0]
print displayName
except ldap.INVALID_CREDENTIALS:
l.unbind()
return 'Wrong username or password'
except ldap.SERVER_DOWN:
return 'AD server not available'
l.unbind()
return 'all is well'
# sys.exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment