#! /usr/bin/env python

import ldap
import ldap.modlist as modlist
import mkpasswd 
# Found at www.grotan.com/project/python/mkpasswd.py 
# NB! to use samba-passwords... take a look at the smbpasswd-module mentioned 
# in mkpasswd.py

base = "dc=example,dc=com"
binddn = "cn=admin," + base
password = "secret"

l = ldap.open("localhost")
l.simpe_bind_s(binddn,password)

# First fetch the list of existing users..
users = l.search_s("ou=people," + base, ldap.SCOPE_SUBTREE,"objectclass=posixAccount")
# res is now a list with tuples (dn,dict)

# Iterate over the result
for user in users:
    userdn = user[0]
    userinfo = user[1]
    old = userinfo['objectClass']
    new = list(old) # Copies the existing objectclasses
    new['objectClass'].append("sambaSamAccount") # add one of these lines for any further objectclasses you want
    # Any new attributes added to this user must be added as key/value in dict
    new['SambaSid'] = '' # How do we generate this ? 2xrid + uidnumber?
    new['sambaNTPassword'] = mkpasswd.mkpasswd("secret",default="nthash") # mkpasswd takes a cleartext-password and returns encrypted password
    new['sambaLMPassword'] = mkpasswd.mkpasswd("secret",default="lmhash")

    attrs = modlist.modifyModlist(old,new)
    try:
        l.modify_s(userdn,attrs)
    except LDAPError,e:
        print "An error occured: " + e

print "Done modifying user objectclasses"
