Search code examples
pythonactive-directoryldappython-ldap

python-ldap and Microsoft Active Directory: connect and delete user


python-ldap newb here. I am trying to do this with the following sample code:

import ldap

## first you must bind so we're doing a simple bind first
try:
l = ldap.open("valid ip")
l.set_option(ldap.OPT_REFERRALS, 0)

l.protocol_version = ldap.VERSION3  
# Pass in a valid username and password to get 
# privileged directory access.
# If you leave them as empty strings or pass an invalid value
# you will still bind to the server but with limited privileges.

username = "cn=administrator, o=joe.local"
password  = "password"

# Any errors will throw an ldap.LDAPError exception 
# or related exception so you can ignore the result
l.simple_bind(username, password)
      except ldap.LDAPError, e:
print e
# handle error however you like


      # The next lines will also need to be changed to support your requirements and directory
      deleteDN = "uid=hihihi, ou=LoginUsers,o=joe.local"
      try:
# you can safely ignore the results returned as an exception 
# will be raised if the delete doesn't work.
l.delete_s(deleteDN)
      except ldap.LDAPError, e:
print e
## handle error however you like

I get various errors:

Using IP of VM:

{'info': '000004DC: LdapErr: DSID-0C0909A2, comment: In order to perform this op
eration a successful bind must be completed on the connection., data 0, v1db1',
'desc': 'Operations error'}

Using localhost or 127.0.0.1 :

{'desc': "Can't contact LDAP server"}
{'desc': "Can't contact LDAP server"}

I have looked at the following S.O. posts with no resolution:

Python-ldap authenication Python-ldap microsoft


Solution

  • According to the documentation, ldap.open is deprecated. You should try ldap.initialize, like the two links you provided. Also, make sure there are no spaces in your distinguished names: "cn=administrator, o=joe.local".

    If that doesn't fix the problem, then make sure to mention which line that error is coming from.