2008-12-21 12 views
19

Come posso creare un account utente locale utilizzando .NET 2.0 e C# e anche essere in grado di impostare "La password non scade mai" in mai.Creazione dell'account utente locale C# e .NET 2.0

Ho provato a utilizzare "Net.exe" utilizzando Process.Start e passando i suoi parametri ma sembra che "l'utente netto" non sia in grado di impostare "Nessuna scadenza mai" in mai.

risposta

21

Leggi questo eccellente articolo CodeProject

Howto: (Almost) Everything In Active Directory via C#

C'è una sezione "Create Account utente" e "Trattare con User Password".

UPDATE:

Per adattare il codice per gli account locali sostituiscono le rispettive linee con questi:

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + 
    Environment.MachineName); 
DirectoryEntry newUser = localMachine.Children.Add("localuser", "user"); 

Qui inizia il frammento di codice originale per gli account di dominio:

public string CreateUserAccount(string ldapPath, string userName, 
    string userPassword) 
{ 
    string oGUID = string.Empty; 
    try 
    {   
     string connectionPrefix = "LDAP://" + ldapPath; 
     DirectoryEntry dirEntry = new DirectoryEntry(connectionPrefix); 
     DirectoryEntry newUser = dirEntry.Children.Add 
      ("CN=" + userName, "user"); 
     newUser.Properties["samAccountName"].Value = userName; 

     int val = (int)newUser.Properties["userAccountControl"].Value; 
     newUser.Properties["userAccountControl"].Value = val | 0x10000; 

     newUser.CommitChanges(); 
     oGUID = newUser.Guid.ToString(); 

     newUser.Invoke("SetPassword", new object[] { userPassword }); 
     newUser.CommitChanges(); 

     dirEntry.Close(); 
     newUser.Close(); 
    } 
    catch (System.DirectoryServices.DirectoryServicesCOMException E) 
    { 
     //DoSomethingwith --> E.Message.ToString();  
    } 
    return oGUID; 
} 

Ci sono alcune specifiche per capire quando si tratta di password degli utenti e confini intorno password come costringere un utente a cambiare la loro password all'accesso successivo, negando all'utente il diritto di modificare i propri password, delle password mai scadere, fino alla scadenza e queste attività possono essere eseguite utilizzando i flag UserAccountControl che sono dimostrati nelle sezioni procedenti.

prega di fare riferimento a questo grande MSDN article: Managing User Passwords per esempi e documentazione per quanto riguarda queste caratteristiche.

CONST       HEX 
------------------------------------------ 
SCRIPT       0x0001 
ACCOUNTDISABLE     0x0002 
HOMEDIR_REQUIRED    0x0008 
LOCKOUT      0x0010 
PASSWD_NOTREQD     0x0020 
PASSWD_CANT_CHANGE    0x0040 
ENCRYPTED_TEXT_PWD_ALLOWED  0x0080 
TEMP_DUPLICATE_ACCOUNT   0x0100 
NORMAL_ACCOUNT     0x0200 
INTERDOMAIN_TRUST_ACCOUNT  0x0800 
WORKSTATION_TRUST_ACCOUNT  0x1000 
SERVER_TRUST_ACCOUNT   0x2000 
DONT_EXPIRE_PASSWORD   0x10000 
MNS_LOGON_ACCOUNT    0x20000 
SMARTCARD_REQUIRED    0x40000 
TRUSTED_FOR_DELEGATION   0x80000 
NOT_DELEGATED     0x100000 
USE_DES_KEY_ONLY    0x200000 
DONT_REQ_PREAUTH    0x400000 
PASSWORD_EXPIRED    0x800000 
TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000 
+0

I collegamenti specificati sono per la directory attiva. Forse non ero chiaro. Voglio cambiare l'account utente locale (il computer non fa parte di una directory attiva). – mrtaikandi

+0

Per quanto mi ricordo dovrebbe valere anche per gli account locali. – splattne

+0

@ Mohammadreza: ho aggiornato la mia risposta. Ora c'è un codice che gestisce gli account locali – splattne

21

Questo codice crea un account locale con la password non scade mai set di opzioni:

 using System.DirectoryServices; 

     DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost"); 
     DirectoryEntries entries = hostMachineDirectory.Children; 
     bool userExists = false; 
     foreach (DirectoryEntry each in entries) 
     { 
      userExists = each.Name.Equals("NewUser", 
      StringComparison.CurrentCultureIgnoreCase); 
      if (systemtestUserExists) 
       break; 
     } 

     if (false == userExists) 
     { 
      DirectoryEntry obUser = entries.Add("NewUser", "User"); 
      obUser.Properties["FullName"].Add("Local user"); 
      obUser.Invoke("SetPassword", "[email protected]"); 
      obUser.Invoke("Put", new object[] {"UserFlags", 0x10000}); 
      obUser.CommitChanges(); 
     } 

Il 0x10000 bandiera significa PasswordNeverExpires.

Ho trascorso molto tempo a capire come creare un account utente locale con la password impostata per non scadere. Sembra che quando si tenta di utilizzare:

int val = (int)newUser.Properties["userAccountControl"].Value; 
newUser.Properties["userAccountControl"].Value = val | 0x10000 

autorizzazioni dalla directory attiva entrano in gioco. Se hai permessi di directory attivi tutto funziona correttamente. Se non si ottiene la proprietà userAccountControl, verrà sempre generato un valore nullo. Cercando di impostare userAccountControl si otterrà un'eccezione "La proprietà della directory non può essere trovata nella cache".

Tuttavia dopo una lunga ricerca in giro ho trovato un'altra proprietà "UserFlags" che deve essere impostata utilizzando Invoke. Puoi usarlo per impostare il flag su un account locale. Ho provato questo codice e ha funzionato su Windows Server 2008.

Spero che questo aiuti

+0

Bello, +1. Un paio di note: primo, DirectoryEntry è usa e getta, quindi è meglio eseguire il wrapping con {}; in secondo luogo, il costruttore DirectoryEntry può assumere un nome macchina remoto se è necessario creare un utente locale su una casella remota. –

0

utilizzando System.DirectoryServices;

DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost"); 
    DirectoryEntries entries = hostMachineDirectory.Children; 
    bool userExists = false; 
    foreach (DirectoryEntry each in entries) 
    { 
     userExists = each.Name.Equals("NewUser", 
     StringComparison.CurrentCultureIgnoreCase); 
     if (systemtestUserExists) 
      break; 
    } 

    if (false == userExists) 
    { 
     DirectoryEntry obUser = entries.Add("NewUser", "User"); 
     obUser.Properties["FullName"].Add("Local user"); 
     obUser.Invoke("SetPassword", "[email protected]"); 
     obUser.Invoke("Put", new object[] {"UserFlags", 0x10000}); 
     obUser.CommitChanges(); 
Problemi correlati