简体   繁体   English

python-ldap和Microsoft Active Directory:连接并删除用户

[英]python-ldap and Microsoft Active Directory: connect and delete user

python-ldap newb here. python-ldap newb在这里。 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: 使用虚拟机IP:

{'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 : 使用localhost或127.0.0.1:

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

I have looked at the following SO posts with no resolution: 我看了以下没有解决的SO帖子:

Python-ldap authenication Python-ldap microsoft Python-ldap身份验证 Python-ldap microsoft

According to the documentation , ldap.open is deprecated. 根据文档 ,不建议使用ldap.open You should try ldap.initialize , like the two links you provided. 您应该尝试ldap.initialize ,就像您提供的两个链接一样。 Also, make sure there are no spaces in your distinguished names: "cn=administrator, o=joe.local" . 另外,请确保您的专有名称中没有空格: "cn=administrator, o=joe.local"

If that doesn't fix the problem, then make sure to mention which line that error is coming from. 如果那不能解决问题,请确保提及错误出自哪一行。

What version of python you use ??. 您使用的是哪个版本的python? The code is pretty old. 代码很旧。 open now is initialize, don't use simple_bind, use simple_bind_s. 现在打开是初始化的,不要使用simple_bind,请使用simple_bind_s。

If you want to make operations like, delete, changepassword in AD, you must first configure TLS connections . 如果要在AD中进行诸如删除,更改密码之类的操作,则必须首先配置TLS连接。 http://araihan.wordpress.com/2009/10/05/windows-server-2008-active-directory-certificate-services-ad-cs/ 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. lcon_emg.passwd_s,不能使用。 You need to simple change de unicodepwd attribute to change the user password in Active directory. 您需要简单的change de unicodepwd属性来更改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 希望这个答案对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM