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

人走茶凉 提交于 2019-12-25 07:59:15

问题


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


回答1:


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.




回答2:


What version of python you use ??. The code is pretty old. open now is initialize, don't use simple_bind, use simple_bind_s.

If you want to make operations like, delete, changepassword in AD, you must first configure TLS connections . http://araihan.wordpress.com/2009/10/05/windows-server-2008-active-directory-certificate-services-ad-cs/

Here is a success connection.

import ldap

LDAP_SERVER_EMG = "ldaps://192.168.0.250"
BIND_DN = "Administrador@emgS.local"
BIND_PASS = "xxxXXXxxxXXXxxx"
USER_BASE = "dc=emgS,dc=local"
try:
   ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, 0)
   lcon_emg = ldap.initialize(LDAP_SERVER_EMG)
   lcon_emg.simple_bind_s(BIND_DN, BIND_PASS)
except ldap.LDAPError, e:
   print e

Then you can delete and change user password.

the lcon_emg.passwd_s, dit not work. You need to simple change de unicodepwd attribute to change the user password in Active directory.

#firs is a good practice to create a dict of all atributes of the user
ad_u = {
        'objectClass': ['top', 'person', 'organizationalPerson', 'user'],  
        'cn': 'User gecos or name',
       'displayName': 'User gecos or name',
       'User Gecos or Name',
       'distinguishedName': 'user distin name',
       'givenName': 'First name i guest',
       'sAMAccountName': 'user_login_name',
       'sn': 'middle name i guest',
        #USER PRIVILEGE, SEE THE DOCUMENTATION OF AD FOR MORE INFORMATION, BECAUSE I DON'T REMEMBER :)
       'userAccountControl': '514',
        #user_login_name, with domain extension
       'userPrincipalName': '%s@emg.local' % 'user_login_name',
       'mail': 'user_login_name@emaildomainorwhatever',
       'employeeID': 'unique_user_number'
       }
mods = ldap.modlist.addModlist(ad_u)

try:
   lcon_emg.add_s(ad_u.get('distinguishedName'),
                  mods)
except Exception, e:
   response.update({'error_ad': 'ActiveD: Error to add user %s' % str(e)})
else:
   response.update({'success_ad': 'ActiveD: Success add user'})

#HERE YOU MAKE THE utf-16-le encode password
unicode_pass = unicode('\"' + kwargs.get('cclara') + '\"', 'iso-8859-1')
password_value = unicode_pass.encode('utf-16-le')
#just change the atribute in the entry you just create
add_pass = [(ldap.MOD_REPLACE, 'unicodePwd', [password_value])]

# 512 will set user account to enabled
#change the user to enabled
mod_acct = [(ldap.MOD_REPLACE, 'userAccountControl', '512')]

try:
    lcon_emg.modify_s(ad_u.get('distinguishedName'), add_pass)
except ldap.LDAPError, error_message:
    response.update({'error_ad_clave': 'ActiveD: Error to gen the pass %s' % str(error_message)})
else:
    response.update({'success_ad_clave': 'ActiveD: Success gen pass'})

try:
    lcon_emg.modify_s(ad_u.get('distinguishedName'), mod_acct)
except ldap.LDAPError, error_message:
    response.update({'error_ad_hab': 'Error to enable user %s' % str(error_message)})
else:
    response.update({'success_ad_hab': 'SUccess enable user'})
lcon_emg.unbind_s()

If you want change the password later.

pad = ('"%s"' % password).encode("utf-16-le")

try:
   mod_attrs = [(ldap.MOD_REPLACE, 'unicodePwd', pad),
                (ldap.MOD_REPLACE,'unicodePwd',pad)]
   lcon_emg.modify_s(rdnad, mod_attrs)
except Exception, e:
     response.update({'error_ad': 'No se pudo cambiar la clave %s' % str(e)})
else:
     response.update({'success_ad': 'Cambio exito en Active Directory'})

I hope this answer help you



来源:https://stackoverflow.com/questions/13636117/python-ldap-and-microsoft-active-directory-connect-and-delete-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!