Sign up to create your own snipts, or login.

Public snipts » Fotinakis's snipts » Change Active Directory password via LDAP modify call

posted on Aug 03, 2009 at 4:56 p.m. EDT in 
  • #!/usr/bin/python
    
    import ldap
    
    host = 'ldaps://ldap.example.com:636'
    
    con = ldap.initialize(host)
    con.set_option( ldap.OPT_X_TLS_DEMAND, True )
    con.set_option( ldap.OPT_DEBUG_LEVEL, 255 )
    
    # Encode the password in UTF-16 Little Endian
    #
    # ASCII "new":     0x6E 0x65 0x77
    # UTF-16 "new":    0x6E 0x00 0x65 0x00 0x77 0x00
    # UTF-16 "new"
    #     with quotes: 0x22 0x00 0x6E 0x00 0x65 0x00 0x77 0x00 0x22 0x00
    #
    # http://msdn.microsoft.com/en-us/library/cc200469%28PROT.10%29.aspx
    #
    # NOTE: The article says to BER encode the password octet stream before
    # sending for change, but doing so causes the server to give its standard
    # "will not perform" error on password change. So, no BER encoding is done here.
    username = 'someUser'
    new_pass = 'ne$wP4assw0rd3!'
    new_password = ('"%s"' % new_pass).encode("utf-16-le")
    
    try:
    	con.simple_bind_s( "admin@ldap.example.com", "password" )
    	
    	# For some reason, two MOD_REPLACE calls are necessary to change the password.
    	# If only one call is performed, both the old and new password will work.
    	mod_attrs = [( ldap.MOD_REPLACE, 'unicodePwd', new_password)],( ldap.MOD_REPLACE, 'unicodePwd', new_password)]
    	con.modify_s('CN=%s,OU=Users,DC=ldap,DC=example,DC=com' % username, mod_attrs)
    except:
    	raise
    else:
    	print "Successfully changed password."
    

    copy | embed

0 Comments

Sign up, or login to leave a comment.