
scoubidou944
|
Réponse acceptée !
Réponse finale : Program.cs
// Get administrator localized group name string strGroupSID = "S-1-5-32-544"; SecurityIdentifier secid = new SecurityIdentifier(strGroupSID); byte[] binaryForm = new byte[256]; secid.GetBinaryForm(binaryForm, 0); string strGroupName = ConvertSIDToNameUtility.GetSIDName(binaryForm);
NetCommandUtility.CreateLocalUser(strAccountName, strDefaultPassword, strFullName, null, strComment); NetCommandUtility.AddLocalUserToGroup(strAccountName, strGroupName); NetCommandUtility.DeleteLocalUser(strAccountName);
NetCommandUtility.cs
using System; using System.Diagnostics; using System.IO; using System.ComponentModel;
namespace CreateWindowsAccount { internal sealed class NetCommandUtility { // These are the Win32 error code for file not found or access denied. const int ERROR_FILE_NOT_FOUND = 2; const int ERROR_ACCESS_DENIED = 5;
private NetCommandUtility() { } ~NetCommandUtility() { }
/// <summary> /// Add a local user user to a local group /// </summary> /// <param name="username">username account</param> /// <param name="groupname">destination group</param> static internal void AddLocalUserToGroup(string username, string groupname) { string strErrorBuffer; string strWindowsPath = Environment.ExpandEnvironmentVariables("%WINDIR%");
Process MyProc = new Process(); MyProc.StartInfo.WorkingDirectory = Path.Combine(strWindowsPath, @"SYSTEM32"); MyProc.StartInfo.FileName = "net.exe"; MyProc.StartInfo.UseShellExecute = false; MyProc.StartInfo.RedirectStandardError = true; MyProc.StartInfo.RedirectStandardInput = true; MyProc.StartInfo.RedirectStandardOutput = true; MyProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string strArgOption1 = " /add "; MyProc.StartInfo.Arguments = string.Format (" localgroup {0} {1} {2}", groupname, username, strArgOption1);
try { bool bResult = MyProc.Start();
MyProc.WaitForExit();
string StdOutput = MyProc.StandardOutput.ReadToEnd(); string ErrOutput = MyProc.StandardError.ReadToEnd(); if (!String.IsNullOrEmpty(ErrOutput)) { Console.WriteLine(ErrOutput); }
MyProc.Close(); } catch (Win32Exception e) { if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND) { strErrorBuffer = string.Format("ERROR : {0} ({1})", e.Message, MyProc.StartInfo.FileName); } else if (e.NativeErrorCode == ERROR_ACCESS_DENIED) { strErrorBuffer = string.Format("ERROR : {0} ({1})", e.Message, MyProc.StartInfo.FileName); } else { strErrorBuffer = string.Format("ERROR : {0} (unknown)", e.Message); } Console.WriteLine(strErrorBuffer); } catch (Exception e) { Console.WriteLine(e.Message + ". Generic exception."); } }
/// <summary> /// Delete a local user /// </summary> /// <param name="username">Username of account to delete</param> static internal void DeleteLocalUser(string username) { string strErrorBuffer; string strWindowsPath = Environment.ExpandEnvironmentVariables("%WINDIR%");
Process MyProc = new Process(); MyProc.StartInfo.WorkingDirectory = Path.Combine(strWindowsPath, @"SYSTEM32"); MyProc.StartInfo.FileName = "net.exe"; MyProc.StartInfo.UseShellExecute = false; MyProc.StartInfo.RedirectStandardError = true; MyProc.StartInfo.RedirectStandardInput = true; MyProc.StartInfo.RedirectStandardOutput = true; MyProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; MyProc.StartInfo.Arguments = " user " + username + @" /DELETE ";
try { bool bResult = MyProc.Start();
MyProc.WaitForExit();
string StdOutput = MyProc.StandardOutput.ReadToEnd(); string ErrOutput = MyProc.StandardError.ReadToEnd(); if (!String.IsNullOrEmpty(ErrOutput)) { Console.WriteLine(ErrOutput); }
MyProc.Close(); } catch (Win32Exception e) { if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND) { strErrorBuffer = string.Format("ERROR : {0} ({1})", e.Message, MyProc.StartInfo.FileName); } else if (e.NativeErrorCode == ERROR_ACCESS_DENIED) { strErrorBuffer = string.Format("ERROR : {0} ({1})", e.Message, MyProc.StartInfo.FileName); } else { strErrorBuffer = string.Format("ERROR : {0} (unknown)", e.Message); } Console.WriteLine(strErrorBuffer); } catch (Exception e) { Console.WriteLine(e.Message + ". Generic exception."); } }
/// <summary> /// Create a local user (added to User group by default) /// </summary> /// <param name="username">Username of account to create</param> /// <param name="password">Password for new account</param> /// <param name="fullname">Full displayed name</param> /// <param name="homedir">User homedirectory</param> /// <param name="comment">Add a comment to user</param> static internal void CreateLocalUser(string username, string password, string fullname, string homedir, string comment) { // DOC : // http://www.ss64.com/nt/netuseroptions.html // http://www.thejackol.com/2004/08/03/create-a-local-windows-user-account-cnet/ // string strErrorBuffer;
if ((!string.IsNullOrEmpty(homedir)) && (!Directory.Exists(homedir))) Directory.CreateDirectory(homedir);
string strWindowsPath = Environment.ExpandEnvironmentVariables("%WINDIR%");
Process MyProc = new Process(); MyProc.StartInfo.WorkingDirectory = Path.Combine(strWindowsPath, @"SYSTEM32"); MyProc.StartInfo.FileName = "net.exe"; MyProc.StartInfo.UseShellExecute = false; MyProc.StartInfo.RedirectStandardError = true; MyProc.StartInfo.RedirectStandardInput = true; MyProc.StartInfo.RedirectStandardOutput = true; MyProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
string strArgPassword = string.Format(@" ""{0}"" ", password); string strArgOption1 = @" /ADD /ACTIVE:YES "; //string strArgOption2 = @" /EXPIRES:NEVER /FULLNAME:" + @"""" + fullname + @""""; string strArgOption2 = string.Format(@" /EXPIRES:NEVER /FULLNAME:""{0}"" ", fullname);
string strArgOption3 = String.Empty; if (!string.IsNullOrEmpty(homedir)) strArgOption3 = @" /HOMEDIR:""" + homedir + @"""";
string strArgOption4 = @" /PASSWORDCHG:NO /PASSWORDREQ:YES"; string strArgOption5 = @" /comment:""" + comment + @"""";
MyProc.StartInfo.Arguments = " user " + username + strArgPassword + strArgOption1 + strArgOption2 + strArgOption3 + strArgOption4 + strArgOption5;
try { bool bResult = MyProc.Start();
MyProc.WaitForExit();
string StdOutput = MyProc.StandardOutput.ReadToEnd(); string ErrOutput = MyProc.StandardError.ReadToEnd(); if (!String.IsNullOrEmpty(ErrOutput)) { Console.WriteLine(ErrOutput); }
MyProc.Close(); } catch (Win32Exception e) { if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND) { strErrorBuffer = string.Format("ERROR : {0} ({1})", e.Message, MyProc.StartInfo.FileName); } else if (e.NativeErrorCode == ERROR_ACCESS_DENIED) { strErrorBuffer = string.Format("ERROR : {0} ({1})", e.Message, MyProc.StartInfo.FileName); } else { strErrorBuffer = string.Format("ERROR : {0} (unknown)", e.Message); } Console.WriteLine(strErrorBuffer); } catch (Exception e) { Console.WriteLine(e.Message + ". Generic exception."); } } } }
ConvertSIDToNameUtility.cs
using System; using System.Runtime.InteropServices; using System.Text;
namespace CreateWindowsAccount { internal sealed class ConvertSIDToNameUtility { private ConvertSIDToNameUtility() {} ~ConvertSIDToNameUtility() { }
const int NO_ERROR = 0; const int ERROR_INSUFFICIENT_BUFFER = 122;
enum SID_NAME_USE { SidTypeUser = 1, SidTypeGroup, SidTypeDomain, SidTypeAlias, SidTypeWellKnownGroup, SidTypeDeletedAccount, SidTypeInvalid, SidTypeUnknown, SidTypeComputer }
[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError = true)] static extern bool LookupAccountSid ( string lpSystemName, [MarshalAs(UnmanagedType.LPArray)] byte[] Sid, System.Text.StringBuilder lpName, ref uint cchName, System.Text.StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse);
static internal string GetSIDName(byte[] sid) { StringBuilder name = new StringBuilder(); uint cchName = (uint)name.Capacity; StringBuilder referencedDomainName = new StringBuilder(); uint cchReferencedDomainName = (uint)referencedDomainName.Capacity; SID_NAME_USE sidUse;
int err = NO_ERROR; if (!LookupAccountSid(null,sid,name,ref cchName,referencedDomainName,ref cchReferencedDomainName,out sidUse)) { err = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); if (err == ERROR_INSUFFICIENT_BUFFER) { name.EnsureCapacity((int)cchName); referencedDomainName.EnsureCapacity((int)cchReferencedDomainName); err = NO_ERROR; if (!LookupAccountSid(null,sid,name,ref cchName,referencedDomainName,ref cchReferencedDomainName,out sidUse)) err = System.Runtime.InteropServices.Marshal.GetLastWin32Error(); } } if (err == 0) Console.WriteLine(@"Found account {0} : {1}\{2}",sidUse,referencedDomainName.ToString(),name.ToString()); else Console.WriteLine(@"Error : {0}",err);
return name.ToString(); } } }
|