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

VB.NET Discussion :

Lecture de clé de registre d'un ordinateur distant [Débutant]


Sujet :

VB.NET

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Analyste Service Client
    Inscrit en
    Octobre 2011
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Analyste Service Client
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Octobre 2011
    Messages : 21
    Points : 8
    Points
    8
    Par défaut Lecture de clé de registre d'un ordinateur distant
    Bonjour,

    Je développe actuellement un outil et j'ai besoin d'aller lire voire modifier une clé de registre sur un ordinateur distant. Je souhaiterais que mon programme permette quand on lui donne un chemin et une clé de registre qu'il affiche via une msgbox le contenu de la valeur DWORD de la clé en question.

    Pour les exemples que je vais proposer je mettrais les deux données en dur dans le programme.

    Cela marche parfaitement quand je le fait sur mon poste via ce code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Dim regVersion As RegistryKey
            Dim keyValue As String
            keyValue = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
            regVersion = Registry.LocalMachine.OpenSubKey(keyValue, False)
            Dim intVersion As Integer = 0
            If (Not regVersion Is Nothing) Then
                intVersion = regVersion.GetValue("ADH", 0)
                regVersion.Close()
            End If
            MsgBox("La Valeur de la clé ADH est : " & intVersion)
    Dans mon exemple cela me retourne bien la valeur ADH, sauf que lorsque je veux faire la même chose sur un ordinateur distant je récupére toujours la valeur minimale -214721....

    Mon code se présente comme ceci :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    Const HKEY_LOCAL_MACHINE = &H80000002
            Dim strComputer = "nomdemachine"
            Dim oReg = GetObject("winmgmts:\\" & strComputer & "\root\default:StdRegProv")
            Dim strKeyPath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
            Dim strValueName = "ADH"
            Dim result = oReg.GetDWORDValue(HKEY_LOCAL_MACHINE, strKeyPath, strValueName)
            MsgBox(result)
    Je ne veux en aucun cas de script vb car je veux integrer cet fonctionnalité dans un outil pré-existant.

    Je vous demande donc de l'aide pour m'aider car je commence a ronger mon bureau de frustration...

    Cordialement,
    Faufoll

  2. #2
    Futur Membre du Club
    Homme Profil pro
    Analyste Service Client
    Inscrit en
    Octobre 2011
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Analyste Service Client
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Octobre 2011
    Messages : 21
    Points : 8
    Points
    8
    Par défaut
    Après avoir testé pas mal de chose il s'est avéré que ceci fonctionnait parfaitement :

    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
    Sub ReadKey(ByVal commandLineArgs As String)
            Select Case PrefixeKey
                Case "HKEY_LOCAL_MACHINE"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.LocalMachine, _
                            commandLineArgs).OpenSubKey(CheminCle)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_CURRENT_USER"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.CurrentUser, _
                            commandLineArgs).OpenSubKey(CheminCle)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_USERS"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.Users, _
                            commandLineArgs).OpenSubKey(CheminCle)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
            End Select
            MsgBox("La valeur de la clé de registre " & CleRegistre & " est : " & environmentKey.GetValue(CleRegistre))
            environmentKey.Close()

    J'ai donc fait Modifier, Ajouter et Supprimer comme fonction et c'est la que je bloque.
    Si Modifier et Ajouter se passe a merveille, impossible de Supprimer.
    Il finit son traitement, ne me sort pas d'erreur mais en me connectant ou même en utilisant ma fonction ReadKey, elle y est toujours.
    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
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    Sub SuppKey(ByVal commandLineArgs As String)
     
            Select Case PrefixeKey
                Case "HKEY_LOCAL_MACHINE"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.LocalMachine, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_CURRENT_USER"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.CurrentUser, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_USERS"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.Users, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
            End Select
            If (MsgBox("Etes-vous sur ?", MsgBoxStyle.OkCancel, "Confirmation de suppression") = MsgBoxResult.Ok) Then
                environmentKey.DeleteSubKeyTree(CleRegistre)
                MsgBox("La clé de registre " & CleRegistre & " a été supprimée")
     
            Else
     
            End If
            environmentKey.Close()
    Le code erreur lorsque je relance une suppression est "La clé n'existe pas"
    Et la je sèche

  3. #3
    Futur Membre du Club
    Homme Profil pro
    Analyste Service Client
    Inscrit en
    Octobre 2011
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Analyste Service Client
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Octobre 2011
    Messages : 21
    Points : 8
    Points
    8
    Par défaut
    Bon ben du coup je me suis débrouillé...
    En fait il fallait supprimer la valeur de la clé avant de supprimer la clé en elle même.
    Ce qui donne :

    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
        Sub SuppKey(ByVal commandLineArgs As String)
     
            Select Case PrefixeKey
                Case "HKEY_LOCAL_MACHINE"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.LocalMachine, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_CURRENT_USER"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.CurrentUser, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_USERS"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.Users, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
            End Select
            If (MsgBox("Etes-vous sur ?", MsgBoxStyle.OkCancel, "Confirmation de suppression") = MsgBoxResult.Ok) Then
                If Not CleRegistre Is Nothing Then
                    environmentKey.DeleteValue(CleRegistre, True)
                    environmentKey.DeleteSubKey(CleRegistre, True)
                    MsgBox("La clé de registre " & CleRegistre & " a été supprimée")
                Else
                    Throw New Exception("Cette clé n'existe pas")
                End If
     
            Else
     
            End If
            environmentKey.Close()
        End Sub



    Par contre si quelqu'un pouvait me dire comment rajouter des paramètres d'authentification Windows en parametres de l'OpenRemoteBaseKey, ce serait sympa.
    Car pour que ca fonctionne, je dois me connecter avec un autre compte et faire un Executer en tant que, c'est assez lourd a force

  4. #4
    Modérateur
    Avatar de DotNetMatt
    Homme Profil pro
    CTO
    Inscrit en
    Février 2010
    Messages
    3 611
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 36
    Localisation : Etats-Unis

    Informations professionnelles :
    Activité : CTO
    Secteur : Finance

    Informations forums :
    Inscription : Février 2010
    Messages : 3 611
    Points : 9 743
    Points
    9 743
    Billets dans le blog
    3
    Par défaut
    Bonjour,

    Avant toute chose, merci de noter que je ne suis pas sûr et certain de ma réponse, car je n'ai actuellement pas la possibilité de tester...

    L'idée, c'est de faire tourner le code en utilisant l'impersonification. Un exemple de code en VB.NET est dispo ici : http://williamfaulkner.co.uk/2009/04...e-a-user-2008/

    Tu appelles la méthode ImpersonateStart(), puis tu mets ton propre code qui va faire les modifs dans le registre, et une fois que tu as tout fini, tu appelles ImpersonateStop().
    Less Is More
    Pensez à utiliser les boutons , et les balises code
    Desole pour l'absence d'accents, clavier US oblige
    Celui qui pense qu'un professionnel coute cher n'a aucune idee de ce que peut lui couter un incompetent.

  5. #5
    Futur Membre du Club
    Homme Profil pro
    Analyste Service Client
    Inscrit en
    Octobre 2011
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Analyste Service Client
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Octobre 2011
    Messages : 21
    Points : 8
    Points
    8
    Par défaut
    Ah !!!! Une réponse !

    Je regarde ça cette après-midi et je fais un retour içi pour valider ou non le truc mais ça à l'air prometteur en tout cas !

  6. #6
    Membre actif Avatar de DeWaRs
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Décembre 2006
    Messages
    291
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Décembre 2006
    Messages : 291
    Points : 269
    Points
    269
    Par défaut
    Hello,

    Je cherchais justement cette source car je l'ai utilisée pour un de mes projets. Cela fonctionne parfaitement avec des comptes d'un domaine, je n'ai pas tester avec un compte local, tiens nous au jus si ca fonctionne dans ton cas

    Cordialement.

    DeWaRs

  7. #7
    Futur Membre du Club
    Homme Profil pro
    Analyste Service Client
    Inscrit en
    Octobre 2011
    Messages
    21
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Analyste Service Client
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Octobre 2011
    Messages : 21
    Points : 8
    Points
    8
    Par défaut
    Et ben ça marche !!!
    Merci beaucoup Matt07 !
    Cela marche en compte admin local ou avec un compte du domaine sans restriction. (J'ai mis le domaine en dur dans mon exemple car je ne me connecterai pas en admin local pour des raisons de sécurité)

    Pour la forme je mets le code final :
    Donc le module Impersonator :

    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
    Imports System
    Imports System.Runtime.InteropServices
    Imports System.Security.Principal
    Imports System.Security.Permissions
    Imports Microsoft.VisualBasic
    <Assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode:=True), Assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name:="FullTrust")> 
     
    Public Class RunAs_Impersonator
    #Region "Private Variables and Enum Constants"
        Private tokenHandle As New IntPtr(0)
        Private dupeTokenHandle As New IntPtr(0)
        Private impersonatedUser As WindowsImpersonationContext
    #End Region
    #Region "Properties"
     
    #End Region
    #Region "Public Methods"
        Public Declare Auto Function CloseHandle Lib "kernel32.dll" (ByVal handle As IntPtr) As Boolean
     
        Public Declare Auto Function DuplicateToken Lib "advapi32.dll" (ByVal ExistingTokenHandle As IntPtr, ByVal SECURITY_IMPERSONATION_LEVEL As Integer, ByRef DuplicateTokenHandle As IntPtr) As Boolean
     
        ' Test harness.
        ' If you incorporate this code into a DLL, be sure to demand FullTrust.
        <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> Public Sub ImpersonateStart(ByVal Domain As String, ByVal userName As String, ByVal Password As String)
            Try
                tokenHandle = IntPtr.Zero
                ' Call LogonUser to obtain a handle to an access token.
                Dim returnValue As Boolean = LogonUser(userName, Domain, Password, 2, 0, tokenHandle)
     
                'check if logon successful
     
                If returnValue = False Then
                    Dim ret As Integer = Marshal.GetLastWin32Error()
                    Console.WriteLine("LogonUser failed with error code : {0}", ret)
                    Throw New System.ComponentModel.Win32Exception(ret)
                    Exit Sub
     
                End If
     
                'Logon succeeded
                ' Use the token handle returned by LogonUser.
                Dim newId As New WindowsIdentity(tokenHandle)
                impersonatedUser = newId.Impersonate()
            Catch ex As Exception
     
                Throw ex
                Exit Sub
            End Try
            'MsgBox(“running as ” & impersonatedUser.ToString & ” — ” & WindowsIdentity.GetCurrent.Name)
     
        End Sub
        <PermissionSetAttribute(SecurityAction.Demand, Name:="FullTrust")> _
        Public Sub ImpersonateStop()
            ' Stop impersonating the user.
     
            impersonatedUser.Undo()
     
            ' Free the tokens.
            If Not System.IntPtr.op_Equality(tokenHandle, IntPtr.Zero) Then
                CloseHandle(tokenHandle)
            End If
            'MsgBox(“running as ” & Environment.UserName)
     
        End Sub
    #End Region
     
    #Region "Private Methods"
        Private Declare Auto Function LogonUser Lib "advapi32.dll" (ByVal lpszUsername As [String], _
        ByVal lpszDomain As [String], ByVal lpszPassword As [String], ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean
     
        <DllImport("kernel32.dll")> Public Shared Function FormatMessage(ByVal dwFlags As Integer, ByRef lpSource As IntPtr, ByVal dwMessageId As Integer, ByVal dwLanguageId As Integer, ByRef lpBuffer As [String], ByVal nSize As Integer, ByRef Arguments As IntPtr) As Integer
        End Function
    #End Region
    End Class

    Et l'appel dans un deuxieme module pour lire/ecrire/supprimer/ajouter une clé :
    (j'ai mis que les deux premiers) :

    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
    Imports Microsoft.Win32
    Imports System.IO
    Imports System.Data.OleDb
    Imports System.Text
    Imports System
    Imports System.Security.Permissions
     
    'Il faut mettre en référence des dll téléchargés depuis le site developpez.com 
    'Ce sont des dll d'aide complète pour l'ensemble des fonctionnalités vb.net 
    'Ici cela me sers a utiliser plus facilement les fichiers ini
    Module ModuleRegistry
        Public MyConnection As OleDbConnection = New OleDbConnection()
        Public MyCommand As OleDbCommand = MyConnection.CreateCommand()
        Public MyReader As OleDbDataReader
        Public CheminCle As String
        Public CleRegistre As String
        Public PrefixeKey As String
        Public environmentKey As RegistryKey
        Public myValue As Object
        Public mypass As String
        Public strUser As String
     
     
        Sub ReadKey(ByVal commandLineArgs As String)
            Dim imp As New RunAs_Impersonator 
            imp.ImpersonateStart("domXXX", ModuleRegistry.strUser, ModuleRegistry.mypass)
     
            Select Case PrefixeKey
                Case "HKEY_LOCAL_MACHINE"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.LocalMachine, _
                            commandLineArgs).OpenSubKey(CheminCle)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_CURRENT_USER"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.CurrentUser, _
                            commandLineArgs).OpenSubKey(CheminCle)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_USERS"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.Users, _
                            commandLineArgs).OpenSubKey(CheminCle)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
            End Select
     
            MsgBox("La valeur de la clé de registre " & CleRegistre & " est : " & environmentKey.GetValue(CleRegistre))
            environmentKey.Close()
            imp.ImpersonateStop()
        End Sub
        Sub ModifKey(ByVal commandLineArgs As String)
            Dim imp As New RunAs_Impersonator
            imp.ImpersonateStart("domXXX", ModuleRegistry.strUser, ModuleRegistry.mypass)
            Select Case PrefixeKey
                Case "HKEY_LOCAL_MACHINE"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.LocalMachine, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_CURRENT_USER"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.CurrentUser, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
                Case "HKEY_USERS"
                    Try
                        environmentKey = RegistryKey.OpenRemoteBaseKey( _
                            RegistryHive.Users, _
                            commandLineArgs).OpenSubKey(CheminCle, True)
                    Catch ex As IOException
                        MsgBox("{0}: {1}", _
                            ex.GetType().Name, ex.Message)
                        Return
                    End Try
            End Select
            myValue = InputBox("Choisir la nouvelle valeur", "EditRegistryKey", 0)
            If myValue Is "" Then myValue = 0
            environmentKey.SetValue(CleRegistre, myValue)
            MsgBox("La valeur de la clé de registre " & CleRegistre & " a été changée en : " & environmentKey.GetValue(CleRegistre))
     
            environmentKey.Close()
            imp.ImpersonateStop()
        End Sub
    Sachant que le current users marche avec le compte fournit dans l'Impersonator donc pas vraiment utile mais bon

    Je passe le sujet en résolu

  8. #8
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2014
    Messages : 8
    Points : 11
    Points
    11
    Par défaut Version c#
    Bonjour
    Excusez moi de revenir sur ce sujet déjà résolu, mais quelqu'un pourrait-il m'aider pour avoir
    ce code dans un autre language (de préférence c#).
    J'ai débuter avec quelque chose mais j'obtiens un message d'erreur. 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
     
    [WebMethod(Description = "Connect to registry")]
            public string ConnectToRegistry(string ServerName)
            {
                string regKeyToGet = null;
                string KeyToRead = null;
                ConnectionOptions co = new ConnectionOptions();
                co.Impersonation = ImpersonationLevel.Impersonate;
                co.Username = PSWConfig.USR;
                co.Password = PSWConfig.PSW;
                ManagementScope scope = new ManagementScope(@"\\" + ServerName + @"\ROOT\CIMV2:StdRegProv", co);
                scope.Connect();
     
                ManagementClass Registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
     
                ManagementBaseObject inParams = Registry.GetMethodParameters("GetStringValue");
                inParams["sSubKeyName"] = regKeyToGet;
                inParams["sValueName"] = KeyToRead;
     
                ManagementBaseObject OutParams = Registry.InvokeMethod("GetStringValue", inParams, null);
                //ManagementBaseObject OutParams = Registry.ToString();
     
                return OutParams["sValue"].ToString();
            }

  9. #9
    Membre actif Avatar de DeWaRs
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Décembre 2006
    Messages
    291
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Décembre 2006
    Messages : 291
    Points : 269
    Points
    269
    Par défaut
    Hello,

    Avec le message d'erreur et a quel ligne il apparait, cela serait mieux

    Cordialement

    DeWaRs

  10. #10
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2014
    Messages : 8
    Points : 11
    Points
    11
    Par défaut
    Bonjour
    Désolé de réagir aussi tard mais je n'avais plus accès à mon serveur-test.
    En gros voici le message d'erreur que j'obtiens quand j'exécute mon code.
    Code que je remets :
    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
    [WebMethod(Description = "Connect to Registry")]
            public string ConnectToRegistry(string ServerName)
            {
                string regKeyToGet = null;
                string KeyToRead = null;
                ConnectionOptions co = new ConnectionOptions();
                co.Impersonation = ImpersonationLevel.Impersonate;
                co.Username = PSWConfig.USR;
                co.Password = PSWConfig.PSW;
                ManagementScope scope = new ManagementScope(@"\\" + ServerName + @"\ROOT\CIMV2:StdRegProv", co);
                scope.Connect();
     
                ManagementClass Registry = new ManagementClass(scope, new ManagementPath("StdRegProv"), null);
     
                ManagementBaseObject inParams = Registry.GetMethodParameters("GetStringValue");
                inParams["sSubKeyName"] = regKeyToGet;
                inParams["sValueName"] = KeyToRead;
     
                ManagementBaseObject OutParams = Registry.InvokeMethod("GetStringValue", inParams, null);
                //ManagementBaseObject OutParams = Registry.ToString();
     
                return OutParams["sValue"].ToString();
            }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    System.Management.ManagementException: Non trouvé 
       à System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
       à System.Management.ManagementObject.Initialize(Boolean getObject)
       à System.Management.ManagementBaseObject.get_wbemObject()
       à System.Management.ManagementObject.get_ClassPath()
       à System.Management.ManagementObject.GetMethodParameters(String methodName, ManagementBaseObject& inParameters, IWbemClassObjectFreeThreaded& inParametersClass, IWbemClassObjectFreeThreaded& outParametersClass)
       à System.Management.ManagementObject.GetMethodParameters(String methodName)
       à MonEssai.Service1.ConnectToRegistry(String ServerName) dans D:\Public\VS2010\ASTools\MonEssai\MonEssai\Service1.asmx.cs:ligne 291
    Merci de m'éclairer

  11. #11
    Membre actif Avatar de DeWaRs
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Décembre 2006
    Messages
    291
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : High Tech - Matériel informatique

    Informations forums :
    Inscription : Décembre 2006
    Messages : 291
    Points : 269
    Points
    269
    Par défaut
    Hello,

    A quelle ligne, dans ton code, correspond la ligne 291 ?

    Cordialement

    DeWaRs

    Edit : je serais toi, je m'assurerais que ton serveur est bien accessible avant de me connecter à celui-ci, ou au moins je ferais un "try catch" sur le scope.connect.

  12. #12
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Février 2014
    Messages
    8
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Février 2014
    Messages : 8
    Points : 11
    Points
    11
    Par défaut Re : Lecture de clé de registre d'un ordinateur distant
    Merci bien DeWaRs
    Je regarde tout ça et je reviens pour donner suite

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

Discussions similaires

  1. [Lazarus] Lecture de clé de registre et problème de concaténation
    Par MikeEagle dans le forum Lazarus
    Réponses: 14
    Dernier message: 29/10/2013, 09h01
  2. Lecture de clé de registre
    Par hannibal.76 dans le forum Général JavaScript
    Réponses: 4
    Dernier message: 07/12/2012, 11h35
  3. Réponses: 3
    Dernier message: 24/04/2007, 15h54
  4. Probleme de lecture de clés de registre
    Par Mac Twist dans le forum MFC
    Réponses: 1
    Dernier message: 06/05/2006, 19h00
  5. [reseaux] récupérer le chemin d'un ordinateur distant
    Par titoulet_perl dans le forum Programmation et administration système
    Réponses: 3
    Dernier message: 26/05/2005, 15h29

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