Création d'un compte Admin [Résolu]

scoubidou944 728 Messages postés mardi 22 avril 2003Date d'inscription 19 janvier 2017 Dernière intervention - 11 sept. 2008 à 20:12 - Dernière réponse : scoubidou944 728 Messages postés mardi 22 avril 2003Date d'inscription 19 janvier 2017 Dernière intervention
- 12 sept. 2008 à 16:01
glop, glop.

j'ai besoin de me créer une petite appli d'administration et qui nécessite de se créer un compte admin local pour la gestion et maintenance.

En me basant sur :
http://www.ss64.com/nt/netuseroptions.html
http://www.thejackol.com/2004/08/03/create-a-local-windows-user-account-cnet/

j'ai pu créer mon compte local qui appartient à Utilisateurs

Sur ma VM, 2000 Pro, si je tape la ligne de commande :
net localgroup Administrateurs MyAdminAccount /add
ca marche.
sur ma machine en Vista Pro (qui appartient à un domaine), je me tape l'erreur 1789 concernant une relation d'approbation avec le domaine.

Dans le 1er cas, le nom du groupe (ie Administrateurs) est codé en dur ce qui est mal vu que sur les versions anglaises, ce sera Administrators.
il semblerait qu'il faille passer par le SID.
Mais est ce la bonne voie :
http://www.pinvoke.net/default.aspx/advapi32.LookupAccountSid

SecurityIdentifier secid = new SecurityIdentifier("S-1-5-32-544");
byte[] binaryForm = new byte[256];
secid.GetBinaryForm(binaryForm, 0);

ensuite il faut chopper son nom pour l'injecteur à la commande NET.exe je dirais ?
thx,
++
vincent

----------------------------
C++ forever
C# amateur
Afficher la suite 

Votre réponse

2 réponses

Meilleure réponse
scoubidou944 728 Messages postés mardi 22 avril 2003Date d'inscription 19 janvier 2017 Dernière intervention - 12 sept. 2008 à 16:01
3
Merci
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>
        /// username account

        /// destination group

        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>
        /// Username of account to delete

        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>
        /// Username of account to create

        /// Password for new account

        /// Full displayed name

        /// User homedirectory

        /// Add a comment to user

        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();
        }
    }
}

Merci scoubidou944 3

codes-sources a aidé 80 internautes ce mois-ci

Commenter la réponse de scoubidou944
scoubidou944 728 Messages postés mardi 22 avril 2003Date d'inscription 19 janvier 2017 Dernière intervention - 12 sept. 2008 à 13:17
0
Merci
bon j'ai avancé un peu ;p
j'ai trouvé ce site :
http://it.toolbox.com/wiki/index.php/How_do_I_create_a_local_user,_add_it_to_the_local_admin_and_add_Active_Directory_Group_to_Local_admins_during_logon%3F

voici leur code mis en forme et sans erreur ;p

On en revient encore au même point, convertir le nom du groupe Administrateur  à partir du SID mais on approche...

try
{
    DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
    DirectoryEntry NewUser = AD.Children.Add("YourUserNameHere", "user");
    NewUser.Invoke("SetPassword", new object[] { "YourPasswordHere" });
    NewUser.Invoke("Put", new object[] { "Description", "YourDescriptionHere" });
    NewUser.CommitChanges();

    DirectoryEntry grp;
    grp = AD.Children.Find("Administrateurs", "group");
    if (grp != null)
    {
        grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
    }
    Console.WriteLine("Account Created Successfully");
    Console.ReadLine();
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message); Console.ReadLine();
}
Commenter la réponse de scoubidou944

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.