Welcome, guest | Sign In | My Account | Store | Cart

This is the basic code to create an account in active directory that shows how to do things like set your own exension attributes, force a reset of the password when the user logs in, and set the home directory. It makes used of python's excellent COM support in win32com.

Python, 26 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import win32com,win32com.client
def add_acct(location,account):
  ad_obj=win32com.client.GetObject(location)

  ad_user=ad_obj.Create('user','cn='+user['login'])
  ad_user.Put('sAMAccountName',user['login'])
  ad_user.Put('userPrincipalName',user['login']+'@email.address.com')
  ad_user.Put('DisplayName',user['last']+' '+user['first']) #fullname
  ad_user.Put('givenName',user['first'])
  ad_user.Put('sn',user['last'])
  ad_user.Put('description','regular account')
  ad_user.Put('physicalDeliveryOfficeName','office 1')
  ad_user.Extensionattribute10='your own attribute'
  ad_user.Put('HomeDirectory',r'\\server1\ '[:-1]+user['login']) 
  ad_user.Put('HomeDrive','H:')
  ad_user.SetInfo();ad_user.GetInfo()
  ad_user.LoginScript='login.bat'
  ad_user.AccountDisabled=0
  ad_user.setpassword('the password')
  ad_user.Put('pwdLastSet',0) #-- force reset of password
  ad_user.SetInfo()


location='LDAP://OU=org1,DC=company,DC=com'
user={'first':'fred','last':'smith','login':'fred123'}
add_acct(location,user)

This bit of python code makes it relatively easy to create a basic account in active directory. Whoever runs this code needs to have appropriate rights to add to active directory. The Setinfo() call at the end for the add_acct function is critical to make the add real. There are other options you can set, consult http://msdn.microsoft.com for more info.

Until the account gets replicated among domain controllers, you may not see the account right away. Other code that depends on the account being created may have to wait if it looks at a domain controller which hasn't got the account yet.

1 comment

Erick Bodine 19 years, 7 months ago  # | flag

Connecting to Exchange Mailbox. You could also connect the user to an existing Exchange Mailbox Store by adding the following after the last SetInfo()

import pythoncom

try:
    ad_user.CreateMailbox('LDAP://'+store_ldap_path)
    ad_user.EmailAddress = user+'@email.address.com'
    ad_user.SetInfo()
    ad_user.Put('msExchUserAccountControl', 2)
    ad_user.SetInfo()
except pythoncom.com_error,(hr,msg,exc,arg):
    print "Problem...."
    print hr, msg, exc, arg

You will need to figure out the LDAP string to the mailbox store. The LDAP string will look something like this (very generally speaking):

'CN=MyStore,CN=MyStorageGroup,CN=InformationStore,CN=MyServer,
CN=Servers,CN=First Administrative Group,CN=Administrative Groups,
CN=MySite,CN=Microsoft Exchange,CN=Services,
CN=Configuration'+location