Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

Sujet : Création d'un compte Admin [ Système / Autre ] (scoubidou944)

jeudi 11 septembre 2008 à 20:12:51 | Création d'un compte Admin

scoubidou944

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

vendredi 12 septembre 2008 à 13:17:01 | Re : Création d'un compte Admin

scoubidou944

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



vendredi 12 septembre 2008 à 16:01:18 | Re : Création d'un compte Admin

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




Cette discussion est classé dans : créer, local, www, admin, compte


Répondre à ce message

Sujets en rapport avec ce message

Créer un compte a rebours. [ par lucasd ] Salut Voilà j'aimerais faire un compte a rebours qui s'afficherais dans une cell de datagrid. Je possède un int représentant des milisecondes. Comm Installer un serveur en local [ par usanfr ] Bonjour,Je cherche à installer un serveur en local ( sous xp pro ) pour créer des pages en asp.net !J'ai installer IIS mais quand je créer une page en Object array declaration and initialisation [ par akaii ] hello I need to pass an array of the object com.phone.www.info in a function so I'm trying to create an instance of this object like this: com.phone.w créer executable [ par cococo84 ] bonjour, j' fini une application winform et je ne sais pas comment créer un executable pour l'utiliser ensuite sur n'importe quel PC! merci d'avance Envoie de fichier sur un serveur distant [ par Rapace ] Bonjour,Je dois créer un programme qui envoie des fichier sur un serveru distant et je ne sais pas quelle méthode utilisé.Je m'explique, j'ai des imag Créer un nouveau composant graphique avec affichage dans le designer [ par cfz ] Bonjour, Etant à la découverte du monde fabuleux de C# et .Net je voudrais créer un nouveau composant "test" dans lequel il y aurait un petit dessin.V repere othonormé c# windowsaplication [ par Kbitnik ] Bonjour à tous, voila j'ai un petit problème en faite je cherche à développer un graphique en faite mais tout d'abord il me faut créer le repére ortho [c#]Impression [ par ShinShin ] Bonjour, J'ai reussi a créer un bouton pour imprimer une form seulement lorsque je lance l'impression cela m'imprime une page blanche. J'ai essaillé [C#] instance de shell32 [ par istice ] bonjourVoila, j'ai un petit problème pour créer une instance de shell32.Dans un petit programme tout simple (juste une forme), si je veux créer une in Nom de la Classe Application [ par nico_fip1 ] Bonjour à tous,Je suis un ancien de C++ 6.0, et je passe maintenant à C#.NetMa question est la suivante :Je souhaite créer un objet (instance d'une cl


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,281 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.