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

Windows Discussion :

Connexion WMI en C


Sujet :

Windows

  1. #1
    Invité
    Invité(e)
    Par défaut Connexion WMI en C
    Bonjour,

    Dans la documentation de l'API Win32, les exemples de connexion à WMI sont écrits en Vbscript ou C++.

    Est-il possible de se connecter à WMI en utilisant C ? Si oui, avez-vous un exemple à me montrer car je n'ai rien trouvé à ce sujet.

    Merci beaucoup.

  2. #2
    Expert éminent sénior
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2005
    Messages
    5 072
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Février 2005
    Messages : 5 072
    Points : 12 118
    Points
    12 118
    Par défaut
    L'API WMI fait partie de Win32 qui est une API en C.
    Les exemples en C++ ne doivent pas vraiment être en C++ mais en C+ (joke -)).
    Donnez-nous l'URL d'un exemple en C++ et on verra si cela n'est pas déjà du C.

  3. #3
    Invité
    Invité(e)
    Par défaut
    Voici l'exemple du MSDN

  4. #4
    Expert éminent sénior
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2005
    Messages
    5 072
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : France, Val de Marne (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Conseil

    Informations forums :
    Inscription : Février 2005
    Messages : 5 072
    Points : 12 118
    Points
    12 118
    Par défaut
    Effectivement, COM obscurcie un peu les choses.
    A l’arrache, le code C devrait ressembler à cela :


    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
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    #include <windows.h>
    #include <stdio.h>
    #include <tchar.h>
    #include <Wbemidl.h>
    #include <WbemCli.h>
    #include <wincred.h>
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	HRESULT hres;
    	IWbemLocator *pLoc = NULL;
    	IWbemServices *pSvc = NULL;
    	IEnumWbemClassObject* pEnumerator = NULL;	 
        IWbemClassObject *pclsObj;
        ULONG uReturn = 0;
    	VARIANT vtProp;
    	BSTR cimv2 = L"\\\\computerName\\root\\cimv2";
    	BSTR Locale = L"MS_409";
        BSTR Authority = L"ntlmdomain:domain";
    	BSTR WQL = L"WQL";
    	BSTR Select = L"Select * from Win32_OperatingSystem";
    
    	// Get the user name and password for the remote computer
        CREDUI_INFO cui;
        TCHAR pszName[CREDUI_MAX_USERNAME_LENGTH+1];
        TCHAR pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1];
        BOOL fSave;
        DWORD dwErr;
    
        // Step 1: --------------------------------------------------
        // Initialize COM. ------------------------------------------
    
        hres =  CoInitializeEx(0, COINIT_MULTITHREADED); 
        if (FAILED(hres))
        {
            /*cout << "Failed to initialize COM library. Error code = 0x" 
                << hex << hres << endl;*/
            return 1;                  // Program has failed.
        }
    
        // Step 2: --------------------------------------------------
        // Set general COM security levels --------------------------
        // Note: If you are using Windows 2000, you need to specify -
        // the default authentication credentials for a user by using
        // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
        // parameter of CoInitializeSecurity ------------------------
    
        hres =  CoInitializeSecurity(
            NULL, 
            -1,                          // COM authentication
            NULL,                        // Authentication services
            NULL,                        // Reserved
            RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
            RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
            NULL,                        // Authentication info
            EOAC_NONE,                   // Additional capabilities 
            NULL                         // Reserved
            );
    
                          
        if (FAILED(hres))
        {
            /*cout << "Failed to initialize security. Error code = 0x" 
                << hex << hres << endl;*/
            CoUninitialize();
            return 1;                    // Program has failed.
        }
        
        // Step 3: ---------------------------------------------------
        // Obtain the initial locator to WMI -------------------------
    
        hres = CoCreateInstance(
            &CLSID_WbemLocator,             
            0, 
            CLSCTX_INPROC_SERVER, 
            &IID_IWbemLocator, (LPVOID *) &pLoc);
     
        if (FAILED(hres))
        {
            /*cout << "Failed to create IWbemLocator object."
                << " Err code = 0x"
                << hex << hres << endl;*/
            CoUninitialize();
            return 1;                 // Program has failed.
        }
    
        // Step 4: -----------------------------------------------------
        // Connect to WMI through the IWbemLocator::ConnectServer method
    
        cui.cbSize = sizeof(CREDUI_INFO);
        cui.hwndParent = NULL;
        // Ensure that MessageText and CaptionText identify
        // what credentials to use and which application requires them.
        cui.pszMessageText = TEXT("Remote computer account information");
        cui.pszCaptionText = TEXT("Enter Account Information");
        cui.hbmBanner = NULL;
        fSave = FALSE;
    
        dwErr = CredUIPromptForCredentials( 
            &cui,                             // CREDUI_INFO structure
            TEXT(""),                         // Target for credentials
            NULL,                             // Reserved
            0,                                // Reason
            pszName,                          // User name
            CREDUI_MAX_USERNAME_LENGTH+1,     // Max number for user name
            pszPwd,                           // Password
            CREDUI_MAX_PASSWORD_LENGTH+1,     // Max number for password
            &fSave,                           // State of save check box
            CREDUI_FLAGS_GENERIC_CREDENTIALS |  // flags
            CREDUI_FLAGS_ALWAYS_SHOW_UI |
            CREDUI_FLAGS_DO_NOT_PERSIST);  
    
        if(dwErr)
        {
            /*cout << "Did not get credentials." << endl;*/
            pLoc->lpVtbl->Release(pLoc);     
            CoUninitialize();
            return 1;      
        }
    
        // Connect to the remote root\cimv2 namespace
        // and obtain pointer pSvc to make IWbemServices calls.
        //---------------------------------------------------------
        // change the computerName and domain 
        // strings below to the full computer name and domain 
        // of the remote computer
    
        hres = pLoc->lpVtbl->ConnectServer(pLoc,
            cimv2,
            pszName,                 // User name
            pszPwd,                  // User password
            Locale,               // Locale             
            NULL,                             // Security flags
            Authority,    // Authority        
            0,                                // Context object 
            &pSvc                             // IWbemServices proxy
            );
    
        // When you have finished using the credentials,
        // erase them from memory.
        SecureZeroMemory(pszName, sizeof(pszName));
        SecureZeroMemory(pszPwd, sizeof(pszPwd));
        
        if (FAILED(hres))
        {
            /*cout << "Could not connect. Error code = 0x" 
                 << hex << hres << endl;*/
            pLoc->lpVtbl->Release(pLoc);     
            CoUninitialize();
            return 1;                // Program has failed.
        }
    
       /* cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;*/
    
    
        // Step 5: --------------------------------------------------
        // Set security levels on a WMI connection ------------------
    
        hres = CoSetProxyBlanket(
           pSvc,                        // Indicates the proxy to set
           RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
           RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
           NULL,                        // Server principal name 
           RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
           RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
           NULL,                        // client identity
           EOAC_NONE                    // proxy capabilities 
        );
    
        if (FAILED(hres))
        {
            /*cout << "Could not set proxy blanket. Error code = 0x" 
                << hex << hres << endl;*/
            pSvc->lpVtbl->Release(pSvc);
            pLoc->lpVtbl->Release(pLoc);     
            CoUninitialize();
            return 1;               // Program has failed.
        }
    
        // Step 6: --------------------------------------------------
        // Use the IWbemServices pointer to make requests of WMI ----
    
        // For example, get the name of the operating system
        hres = pSvc->lpVtbl->ExecQuery(pSvc,
            WQL, 
            Select,
            WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
            NULL,
            &pEnumerator);
        
        if (FAILED(hres))
        {
            /*cout << "Query for operating system name failed."
                << " Error code = 0x" 
                << hex << hres << endl;*/
            pSvc->lpVtbl->Release(pSvc);
            pLoc->lpVtbl->Release(pLoc);
            CoUninitialize();
            return 1;               // Program has failed.
        }
    
        // Step 7: -------------------------------------------------
        // Get the data from the query in step 6 -------------------
        while (pEnumerator)
        {
            HRESULT hr = pEnumerator->lpVtbl->Next(pEnumerator,WBEM_INFINITE, 1, 
                &pclsObj, &uReturn);
    
            if(0 == uReturn)
            {
                break;
            }
    
            // Get the value of the Name property
            hr = pclsObj->lpVtbl->Get(pclsObj,L"Name", 0, &vtProp, 0, 0);
            //wcout << " OS Name : " << vtProp.bstrVal << endl;
    
            // Get the value of the FreePhysicalMemory property
            hr = pclsObj->lpVtbl->Get(pclsObj,L"FreePhysicalMemory",
                0, &vtProp, 0, 0);
            /*wcout << " Free physical memory (in kilobytes): "
                << vtProp.uintVal << endl;*/
            VariantClear(&vtProp);
        }
    
        // Cleanup
        // ========
        
        pSvc->lpVtbl->Release(pSvc);
        pLoc->lpVtbl->Release(pLoc);
        pEnumerator->lpVtbl->Release(pEnumerator);
        pclsObj->lpVtbl->Release(pclsObj);
        CoUninitialize();
    
        return 0;   // Program successfully completed.
    
    }

  5. #5
    Invité
    Invité(e)
    Par défaut
    Donc j'en déduis que ça doit être faisable en C.
    Merci beaucoup pour ta réponse, ça me donne un bon point de départ.

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

Discussions similaires

  1. WMI probleme de connexion a distance
    Par pepefourras dans le forum MFC
    Réponses: 9
    Dernier message: 15/12/2011, 02h44
  2. Exception pour connexion à distance WMI
    Par mithrendil dans le forum ASP.NET
    Réponses: 0
    Dernier message: 23/07/2009, 17h21
  3. Connexion WMI sur un machine distante
    Par Dr_shaman dans le forum Windows Forms
    Réponses: 2
    Dernier message: 02/07/2008, 14h22
  4. [WMI]Problème de connexion
    Par vincentlec dans le forum Delphi
    Réponses: 1
    Dernier message: 23/05/2007, 17h38
  5. Problème de connexion WMI avec Windows XP
    Par Against Me! dans le forum API, COM et SDKs
    Réponses: 2
    Dernier message: 24/05/2005, 09h28

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