다음을 통해 공유


예: WMI 애플리케이션 만들기

이 항목의 절차 및 코드 예제를 사용하여 COM 초기화를 수행하고, 로컬 컴퓨터에서 WMI에 연결하고, 일부 데이터를 읽고, 정리하는 완전한 WMI 클라이언트 애플리케이션을 만들 수 있습니다. 원격 컴퓨터 WMI에 연결하면 원격 컴퓨터에서 데이터를 가져오는 방법을 설명합니다.

다음 절차에는 모든 C++ WMI 애플리케이션에 필요한 모든 단계가 포함됩니다.

  1. coInitializeEx호출하여 COM 매개 변수를 초기화합니다.

    자세한 내용은 WMI 애플리케이션대한 COM 초기화를 참조하세요.

  2. CoInitializeSecurity호출하여 COM 프로세스 보안을 초기화합니다.

    자세한 내용은 C++사용하여 기본 프로세스 보안 수준 설정을 참조하세요.

  3. IWbemLocator::ConnectServer호출하여 지정된 호스트 컴퓨터의 네임스페이스(간단한 경우의 로컬 컴퓨터)에 대한 IWbemServices 대한 포인터를 가져옵니다.

    원격 컴퓨터에 연결하려면(예: Computer_A) 다음 개체 경로 매개 변수를 사용합니다.

    _bstr_t(L"\\COMPUTER_A\ROOT\\CIMV2")
    

    자세한 내용은 WMI 네임스페이스대한 연결 만들기를 참조하세요.

  4. CoSetProxyBlanket호출하여 WMI 서비스가 클라이언트를 가장할 수 있도록 IWbemServices 프록시 보안을 설정합니다.

    자세한 내용은 WMI 연결보안 수준 설정을 참조하세요.

  5. IWbemServices 포인터를 사용하여 WMI를 요청합니다. 예를 들어 모든 Win32_Service 인스턴스를 쿼리하여 중지된 서비스를 확인합니다.

    자세한 내용은 클래스 및 인스턴스 정보 조작, WMI쿼리 및 WMI 이벤트 수신참조하세요.

  6. 개체 및 COM을 정리합니다.

    자세한 내용은 WMI 애플리케이션 정리 및 종료참조하세요.

다음 예제 코드는 전체 WMI 클라이언트 애플리케이션입니다.


#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>

#pragma comment(lib, "wbemuuid.lib")

int main(int argc, char **argv)
{
    HRESULT hres;

    // 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.
    }

    // Initialize 
    hres =  CoInitializeSecurity(
        NULL,     
        -1,      // COM negotiates service                  
        NULL,    // Authentication services
        NULL,    // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,    // authentication
        RPC_C_IMP_LEVEL_IMPERSONATE,  // 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.
    }

    // Obtain the initial locator to Windows Management
    // on a particular host computer.
    IWbemLocator *pLoc = 0;

    hres = CoCreateInstance(
        CLSID_WbemLocator,             
        0, 
        CLSCTX_INPROC_SERVER, 
        IID_IWbemLocator, (LPVOID *) &pLoc);
 
    if (FAILED(hres))
    {
        cout << "Failed to create IWbemLocator object. "
            << "Error code = 0x"
            << hex << hres << endl;
        CoUninitialize();
        return 1;       // Program has failed.
    }

    IWbemServices *pSvc = 0;

    // Connect to the root\cimv2 namespace with the
    // current user and obtain pointer pSvc
    // to make IWbemServices calls.

    hres = pLoc->ConnectServer(
        
        _bstr_t(L"ROOT\\CIMV2"), // WMI namespace
        NULL,                    // User name
        NULL,                    // User password
        0,                       // Locale
        NULL,                    // Security flags                 
        0,                       // Authority       
        0,                       // Context object
        &pSvc                    // IWbemServices proxy
        );                              
    
    if (FAILED(hres))
    {
        cout << "Could not connect. Error code = 0x" 
            << hex << hres << endl;
        pLoc->Release();     
        CoUninitialize();
        return 1;                // Program has failed.
    }

    cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;

    // Set the IWbemServices proxy so that impersonation
    // of the user (client) occurs.
    hres = CoSetProxyBlanket(
       
       pSvc,                         // the proxy to set
       RPC_C_AUTHN_WINNT,            // authentication service
       RPC_C_AUTHZ_NONE,             // authorization service
       NULL,                         // Server principal name
       RPC_C_AUTHN_LEVEL_CALL,       // authentication level
       RPC_C_IMP_LEVEL_IMPERSONATE,  // impersonation level
       NULL,                         // client identity 
       EOAC_NONE                     // proxy capabilities     
    );

    if (FAILED(hres))
    {
        cout << "Could not set proxy blanket. Error code = 0x" 
             << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }


    // Use the IWbemServices pointer to make requests of WMI. 
    // Make requests here:

    // For example, query for all the running processes
    IEnumWbemClassObject* pEnumerator = NULL;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"), 
        bstr_t("SELECT * FROM Win32_Process"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 
        NULL,
        &pEnumerator);
    
    if (FAILED(hres))
    {
        cout << "Query for processes failed. "
             << "Error code = 0x" 
             << hex << hres << endl;
        pSvc->Release();
        pLoc->Release();     
        CoUninitialize();
        return 1;               // Program has failed.
    }
    else
    { 
        IWbemClassObject *pclsObj;
        ULONG uReturn = 0;
   
        while (pEnumerator)
        {
            hres = pEnumerator->Next(WBEM_INFINITE, 1, 
                &pclsObj, &uReturn);

            if(0 == uReturn)
            {
                break;
            }

            VARIANT vtProp;

            // Get the value of the Name property
            hres = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
            wcout << "Process Name : " << vtProp.bstrVal << endl;
            VariantClear(&vtProp);
            
            pclsObj->Release();
            pclsObj = NULL;
        }
         
    }
 
    // Cleanup
    // ========
    
    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();  
    
    CoUninitialize();

    return 0;   // Program successfully completed.
}