IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Dotnet Discussion :

Process.start info avec utilisateur du domaine erreur


Sujet :

Dotnet

  1. #1
    Membre habitué
    Inscrit en
    Juin 2007
    Messages
    362
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 362
    Points : 141
    Points
    141
    Par défaut Process.start info avec utilisateur du domaine erreur
    Bonjour,

    Question simple, je pense que l'erreur est trop grosse pour que je la vois
    Je cherche à lancer un script vbs via cscript avec la commande Process.Start avec un utilisateur d'un domaine.

    Voici mon code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
     
     
    System.Diagnostics.Process myProc = new System.Diagnostics.Process();
                        myProc.StartInfo.CreateNoWindow = false;
                        myProc.StartInfo.LoadUserProfile = false;
                        myProc.StartInfo.FileName = @"cscript.exe";
                        myProc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
                        myProc.StartInfo.Domain = "myDomain.Local";
     
                        myProc.StartInfo.UserName = @"myDomain.Local\svc_Migrate";
                        SecureString strPwd = GetSecureString("myPassword");
                        myProc.StartInfo.Password = strPwd;
     
                        string strP = Directory.GetCurrentDirectory();
     
                        myProc.StartInfo.Arguments = strP + @"\Test1.vbs";
                        myProc.StartInfo.UseShellExecute = false;
     
                        Console.WriteLine(myProc.StartInfo.WorkingDirectory);
                        Console.WriteLine(myProc.StartInfo.Arguments);
     
                        try
                        {
                            myProc.Start();
                            myProc.WaitForExit();
                        }
                        catch (Exception e) { Console.WriteLine(e.Message); }
    Ce code fonctionne quand je n'utilise pas les infos liés à mon domaine.
    Dès que j'ajoute l'utilisateur, j'ai une erreur au lancement "utilisateur inconnu ou password incorrect".

    L'utilisateur & le mot de passe fonctionne car j'ai ouvert une session utilisateur avec,

    Merci d'avance

  2. #2
    Membre expert Avatar de jopopmk
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2011
    Messages
    1 856
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 1 856
    Points : 3 570
    Points
    3 570
    Par défaut
    Salut,

    as-tu essayé de mettre le domain dans l'attribut Domain de ton ProcessStartInfo (et en mettant que le user dans UserName) ?
    Es-tu sûr de ton utilisation de SecureString ? Quand je regarde la classe dans la MSDN elle semble travailler plutôt sur des buffer de char, et j'ai pas trouvé de référence probante pour GetSecureString.

    NB : le @ avant le littéral pour FileName est inutile,
    la concat' pour ton fichier vbs ne semble pas bien utile non plus (tu concat' avec le pwd).
    Plus je connais de langages, plus j'aime le C.

  3. #3
    Membre habitué
    Inscrit en
    Juin 2007
    Messages
    362
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 362
    Points : 141
    Points
    141
    Par défaut
    Pardon j'ai omis du code pour SecureString, c'est une classe qui me convertit une chaîne en SecureString:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    private static SecureString GetSecureString(string str)
            {
                SecureString secureString = new SecureString();
                foreach (char ch in str)
                {
                    secureString.AppendChar(ch);
                }
                secureString.MakeReadOnly();
                return secureString;
            }
    J'ai essayé le domaine dans le UserName. Rien de plus.

    J'ai avancé sur l'utilisation d'une classe Impersonate, mais j'ai une erreur de type "Directory non valid" dès que je l'utilise.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
     
    // This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
    // IMPORTANT NOTES:
    // This sample requests the user to enter a password on the console screen.
    // Because the console window does not support methods allowing the password to be masked,
    // it will be visible to anyone viewing the screen.
    // On Windows Vista and later this sample must be run as an administrator. 
     
     
    using System;
    using System.Runtime.InteropServices;
    using System.Security.Principal;
    using System.Security.Permissions;
    using Microsoft.Win32.SafeHandles;
    using System.Runtime.ConstrainedExecution;
    using System.Security;
    using System.IO;
     
    public class ImpersonationDemo
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
     
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);
     
        // Test harness.
        // If you incorporate this code into a DLL, be sure to demand FullTrust.
        [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
        public static void Main(string[] args)
        {
            SafeTokenHandle safeTokenHandle;
            try
            {
                string userName, domainName;
                // Get the user token for the specified user, domain, and password using the
                // unmanaged LogonUser method.
                // The local machine name can be used for the domain name to impersonate a user on this machine.
                Console.Write("Enter the name of the domain on which to log on: ");
                //domainName = Console.ReadLine();
                domainName=@"myDomain";
     
                Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
                //userName = Console.ReadLine();
                userName = @"svc_migrate";
     
                Console.Write("Enter the password for {0}: ", userName);
     
                const int LOGON32_PROVIDER_DEFAULT = 0;
                //This parameter causes LogonUser to create a primary token.
                const int LOGON32_LOGON_INTERACTIVE = 2;
     
                // Call LogonUser to obtain a handle to an access token.  Console.ReadLine()
                bool returnValue = LogonUser(userName, domainName, "myPassword",
                    LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                    out safeTokenHandle);
     
                Console.WriteLine("LogonUser called.");
     
                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    Console.WriteLine("LogonUser failed with error code : {0}", ret);
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
                    Console.WriteLine("Value of Windows NT token: " + safeTokenHandle);
     
                    // Check the identity.
                    Console.WriteLine("Before impersonation: "
                        + WindowsIdentity.GetCurrent().Name);
                    // Use the token handle returned by LogonUser.
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
     
                            System.Diagnostics.Process myProc = new System.Diagnostics.Process();
                            myProc.StartInfo.CreateNoWindow = false;
                            myProc.StartInfo.LoadUserProfile = false;
     
                            myProc.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
     
     
                            string strP = Directory.GetCurrentDirectory();
     
     
                            myProc.StartInfo.Arguments = "cscript //nologo Test1.vbs";
                            myProc.StartInfo.UseShellExecute = false;
     
                            myProc.StartInfo.FileName = @"cmd.exe";
     
                            Console.WriteLine(myProc.StartInfo.WorkingDirectory);
                            Console.WriteLine(myProc.StartInfo.Arguments);
     
                            Console.WriteLine(myProc.StartInfo.FileName);
                            try
                            {
                                myProc.Start();
                                myProc.WaitForExit();
                            }
                            catch (Exception e) { Console.WriteLine(e.Message); }
     
     
                            // Check the identity.
                            Console.WriteLine("After impersonation: "
                                + WindowsIdentity.GetCurrent().Name);
                        }
                    }
                    // Releasing the context object stops the impersonation
                    // Check the identity.
                    Console.WriteLine("After closing the context: " + WindowsIdentity.GetCurrent().Name);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occurred. " + ex.Message);
            }
            Console.ReadKey();
        }
    }
    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        {
        }
     
        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);
     
        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }

  4. #4
    Membre habitué
    Inscrit en
    Juin 2007
    Messages
    362
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 362
    Points : 141
    Points
    141
    Par défaut
    Erreur solutionnée.

    Sur le paramètre WorkingDirectory, il faut ajouter un "\" à la fin du chemin.

  5. #5
    Membre expert Avatar de jopopmk
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2011
    Messages
    1 856
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 1 856
    Points : 3 570
    Points
    3 570
    Par défaut
    Fallait le trouver ! Je reviens de la fiche MSDN de la propriété et il n'y aucune remarque sur le sujet, bien vu.
    Plus je connais de langages, plus j'aime le C.

  6. #6
    Membre habitué
    Inscrit en
    Juin 2007
    Messages
    362
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 362
    Points : 141
    Points
    141
    Par défaut
    Tu sais si on peut bypasser le prompt de l'UAC qui demande d'autoriser l'application à modifier l'ordinateur?

    En sachant qu'avec le Process.start je suis avec un compte admin, donc je suis censé pouvoir modifier l'ordinateur?

  7. #7
    Membre expert Avatar de jopopmk
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Mars 2011
    Messages
    1 856
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mars 2011
    Messages : 1 856
    Points : 3 570
    Points
    3 570
    Par défaut
    Ce qu'il y c'est que tu n'es pas un "vrai admin", c'est pour ça qu'il y a toujours le prompt.
    Et activer le vrai admin n'est ni simple, ni conseillé.
    Du coup je pense que ce n'est simplement pas possible.

    Tu peux ouvrir un nouveau sujet pour poser ta question (celle-ci étant en résolue les helpers viendront moins),
    peut-être que d'autres auront une réponse plus intéressante pour toi
    Plus je connais de langages, plus j'aime le C.

  8. #8
    Membre habitué
    Inscrit en
    Juin 2007
    Messages
    362
    Détails du profil
    Informations forums :
    Inscription : Juin 2007
    Messages : 362
    Points : 141
    Points
    141
    Par défaut
    Je vais quand même l'ouvrir, mais je pense aussi que ce n'est pas possible (sans désactiver réellement l'uac).

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [VB.NET 1.1] Ping silencieux avec Process.Start()
    Par toniolol dans le forum Windows Forms
    Réponses: 6
    Dernier message: 30/09/2008, 13h35
  2. Réponses: 4
    Dernier message: 02/04/2008, 15h19
  3. Copier un fichier sur le réseau avec un autre utilisateur du domaine
    Par Corben dans le forum VB 6 et antérieur
    Réponses: 0
    Dernier message: 30/01/2008, 16h19
  4. Probleme avec Process.Start
    Par lucyole dans le forum VB.NET
    Réponses: 4
    Dernier message: 03/01/2008, 18h42
  5. Process.Start génère une erreur
    Par jerome.fortias dans le forum C#
    Réponses: 6
    Dernier message: 17/09/2007, 15h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo