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

C# Discussion :

Exécuter une commande PowerShell en remote via une application c#


Sujet :

C#

  1. #1
    Nouveau Candidat au Club
    Homme Profil pro
    Analyste d'exploitation
    Inscrit en
    Juillet 2011
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Analyste d'exploitation
    Secteur : Service public

    Informations forums :
    Inscription : Juillet 2011
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Exécuter une commande PowerShell en remote via une application c#
    Bonjour à tous,

    Voici mon problème :

    J'aimerais écrire une petite application capable d'exécuter une cmdlet Powershell, voir un script PowerShell sur une machine distante !

    J'ai écris ceci en me basant sur quelques articles du net :

    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
                SecureString pwd = new SecureString();
                foreach (char c in "mypassword!".ToCharArray())
    	        {
    	            pwd.AppendChar(c);
    	        }
                PSCredential cred = new PSCredential("MyUserName", pwd);
     
                // Create a WSManConnectionInfo object using the default constructor to 
                // connect to the "localhost". The WSManConnectionInfo object can also 
                // specify connections to remote computers.
     
                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(string.Format("http://{0}:5985/wsman", textBox2.Text)), "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", cred);
     
                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Negotiate;
     
     
                // Create a remote runspace pool that uses the WSManConnectionInfo object.  
                // The minimum runspaces value of 1 specifies that Windows PowerShell will 
                // keep at least 1 runspace open. The maximum runspaces value of 2 specifies
                // that Windows PowerShell will keep a maximum of 2 runspaces open at the 
                // same time so that two commands can be run concurrently.
                using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(connectionInfo)) 
                {
                    // Call the Open() method to open a runspace from the pool and establish 
                    // the connection. 
                    remoteRunspace.Open();
     
                    // Call the Create() method to create a pipeline, call the AddCommand(string) 
                    // method to add the "get-process" command, and then call the BeginInvoke() 
                    // method to run the command asynchronously using a runspace of the pool.
                    PowerShell gpsCommand = PowerShell.Create().AddCommand("get-process");
                    gpsCommand.Runspace = remoteRunspace;
                    IAsyncResult gpsCommandAsyncResult = gpsCommand.BeginInvoke();
                    ////<SnippetRemoteRunspacePool01CreatePowerShell01/>
     
                    // The previous call does not block the current thread because it is 
                    // running asynchronously. Because the remote runspace pool can open two 
                    // runspaces, the second command can be run.
                    PowerShell getServiceCommand = PowerShell.Create().AddCommand("get-service");
                    getServiceCommand.Runspace = remoteRunspace;
                    IAsyncResult getServiceCommandAsyncResult = getServiceCommand.BeginInvoke();
     
                    // When you are ready to handle the output, wait for the command to complete 
                    // before extracting results. A call to the EndInvoke() method will block and return 
                    // the output.
                    PSDataCollection<PSObject> gpsCommandOutput = gpsCommand.EndInvoke(gpsCommandAsyncResult);
     
                    // Process the output as needed.
                    if ((gpsCommandOutput != null) && (gpsCommandOutput.Count > 0))
                    {
                        Console.WriteLine("The first output from running get-process command: ");
                        Console.WriteLine(
                                          "Process Name: {0} Process Id: {1}",
                                          gpsCommandOutput[0].Properties["ProcessName"].Value,
                                          gpsCommandOutput[0].Properties["Id"].Value);
                        Console.WriteLine();
                    }
     
                    // Now process the output from second command. As discussed previously, wait 
                    // for the command to complete before extracting the results.
                    PSDataCollection<PSObject> getServiceCommandOutput = getServiceCommand.EndInvoke(
                                    getServiceCommandAsyncResult);
     
                    // Process the output of the second command as needed.
                    if ((getServiceCommandOutput != null) && (getServiceCommandOutput.Count > 0))
                    {
                        Console.WriteLine("The first output from running get-service command: ");
                        Console.WriteLine(
                                          "Service Name: {0} Description: {1} State: {2}",
                                          getServiceCommandOutput[0].Properties["ServiceName"].Value,
                                          getServiceCommandOutput[0].Properties["DisplayName"].Value,
                                          getServiceCommandOutput[0].Properties["Status"].Value);
                    }
     
                    // Once done with running all the commands, close the remote runspace pool.
                    // The Dispose() (called by using primitive) will call Close(), if it
                    // is not already called.
                    remoteRunspace.Close();
                }
            }
    Je reçois le message d'erreur suivant lorsqu'il tente d'exécuter remoteRunspace.Open() :
    Connecting to remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
    Quelqu'un a une idée ?

    Merci

  2. #2
    Futur Membre du Club
    Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Janvier 2010
    Messages
    6
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Janvier 2010
    Messages : 6
    Points : 5
    Points
    5
    Par défaut Les prérequis pour le remote powershell
    Salut,

    as-tu essayé de te connecter par la console en remote ?

    Sinon il y a quelques pré-requis pour effectuer du powershell en remote:
    - Même domaine windows des 2 machines.
    - Le serveur accédé doit être "préparé": Enable-PSRemoting sur le serveur
    - Port 5985 autorisé (si pare-feu ou autre)
    - La station qui accède en remote doit être autorisé sur le serveur avec cette commande: winrm set winrm/config/client `@`{TrustedHosts=`"`*`"`}
    - Regarde si ton user a accès sur le serveur avec la commande: get-user "userName" | fl RemotePowershellEnabled
    => sinon Set-User "username" -RemotePowerShellEnabled $True

    Tiens moi au courant.
    De mon côté j'essaie de changer mon code pour faire de l'asynchrone au lieu du synchrone pour le remote powershell, donc ça pourrait être cool de se tenir informé de nos avancements si tu bosses encore la dessus.

    Bonne soirée.

    olivier.

Discussions similaires

  1. [PowerShell] executez une commande powershell via le task scheduler Windows
    Par secoto dans le forum Scripts/Batch
    Réponses: 1
    Dernier message: 05/06/2014, 13h56
  2. Réponses: 1
    Dernier message: 17/11/2010, 19h42
  3. Recupération d'un sortie standard via une commande ssh.
    Par yanndan dans le forum Administration système
    Réponses: 1
    Dernier message: 28/08/2006, 16h56
  4. Créer un dossier via une commande PHP
    Par budylove dans le forum Langage
    Réponses: 2
    Dernier message: 27/04/2006, 13h45
  5. Réponses: 6
    Dernier message: 09/11/2005, 17h29

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