Create a local user

The following will check to see if a user exists already and if not create the user, a directory and assign them modify rights to that directory.

import clr import System from System.IO import * from System.Security.AccessControl import * clr.AddReferenceByPartialName("System.DirectoryServices") from System.DirectoryServices import *

def test_user_exist(root,user): try: test = root.Children.Find(user) except: # User does not exist result = 0 else: result = 1 return result

def create_user(root,user,description,password): newuser = root.Children.Add(user,"user") newuser.Invoke("SetPassword", password) newuser.CommitChanges newuser.Properties["FullName"].Value=description newuser.Properties["Description"].Value=description flags = newuser.Properties["UserFlags"].Value newuser.Properties["UserFlags"].Value = flags|64|65536 newuser.CommitChanges

def add_rights(user,path,rights): account = System.Security.Principal.NTAccount(user) dir_info = DirectoryInfo(path) dir_sec = Directory.GetAccessControl(path) new_sec = FileSystemAccessRule(account,rights,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow) dir_sec.AddAccessRule(new_sec) dir_info.SetAccessControl(dir_sec)

root = System.DirectoryServices.DirectoryEntry("WinNT://" + System.Environment.MachineName + ",computer") username = "newuser"

if not(test_user_exist(root,username)): create_user(root,username,"A New User","MyPassword")

if not Directory.Exists("c:\\home\\newuser"): Directory.CreateDirectory("c:\\home\\newuser")

add_rights(username,"c:\\home\\newuser",FileSystemRights.Modify)

Notes:
 * The options included on the UserFlags lines will create an account where the user can't change the password and it does not expire. If you don't what that behaviour then remove both lines.
 * This will create the user on the local computer, if you want to work on a remote computer replace System.Environment.MachineName.

Back to Contents.