2014-01-14 7 views
0
  1. Win32 NetworkAdapter, Win32_SignedDriver, C++에서 WMI를 사용하여 WIN32_NetworkAdapter에서 값을 검색하는 방법은 무엇입니까? 쿼리 후 값에 액세스하는 데 사용 된 VARIANT를 이해할 수 없습니다.

답변

3

MSDN에는 WMI and C++에 대한 많은 리소스가 있으며, C++에서 WMI를 처음 사용하는 경우 WMI Delphi Code Creator을 사용하면 C++ 코드를 생성하여 WMI 클래스, 이벤트 및 메서드에 액세스 할 수 있습니다.

#include "stdafx.h" 
#define _WIN32_DCOM 
#include <iostream> 
using namespace std; 
#include <comdef.h> 
#include <Wbemidl.h> 
#pragma comment(lib, "wbemuuid.lib") 

//CREDENTIAL structure 
//http://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v=vs.85%29.aspx 
#define CRED_MAX_USERNAME_LENGTH   513 
#define CRED_MAX_CREDENTIAL_BLOB_SIZE  512 
#define CREDUI_MAX_USERNAME_LENGTH CRED_MAX_USERNAME_LENGTH 
#define CREDUI_MAX_PASSWORD_LENGTH (CRED_MAX_CREDENTIAL_BLOB_SIZE/2) 


#pragma argsused 
int main(int argc, char* argv[]) 
{ 
    wchar_t pszName[CREDUI_MAX_USERNAME_LENGTH+1] = L"user"; 
    wchar_t pszPwd[CREDUI_MAX_PASSWORD_LENGTH+1] = L"password"; 
    BSTR strNetworkResource; 
    //To use a WMI remote connection set localconn to false and configure the values of the pszName, pszPwd and the name of the remote machine in strNetworkResource 
    bool localconn = true; 
    strNetworkResource = localconn ? L"\\\\.\\root\\CIMV2" : L"\\\\remote--machine\\root\\CIMV2"; 

    COAUTHIDENTITY *userAcct = NULL ; 
    COAUTHIDENTITY authIdent; 

    // Initialize COM. ------------------------------------------ 

    HRESULT hres; 
    hres = CoInitializeEx(0, COINIT_MULTITHREADED); 
    if (FAILED(hres)) 
    { 
     cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl; 
     cout << _com_error(hres).ErrorMessage() << endl; 
     cout << "press enter to exit" << endl; 
     cin.get();  
     return 1;     // Program has failed. 
    } 

    // Set general COM security levels -------------------------- 

    if (localconn) 
     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 
      ); 
    else 
     hres = CoInitializeSecurity(
      NULL, 
      -1,       // COM authentication 
      NULL,      // Authentication services 
      NULL,      // Reserved 
      RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication 
      RPC_C_IMP_LEVEL_IDENTIFY, // 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; 
     cout << _com_error(hres).ErrorMessage() << endl; 
     CoUninitialize(); 
     cout << "press enter to exit" << endl; 
     cin.get();  
     return 1;     // Program has failed. 
    } 

    // Obtain the initial locator to WMI ------------------------- 

    IWbemLocator *pLoc = NULL; 
    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; 
     cout << _com_error(hres).ErrorMessage() << endl; 
     CoUninitialize();  
     cout << "press enter to exit" << endl; 
     cin.get();  
     return 1;     // Program has failed. 
    } 

    // Connect to WMI through the IWbemLocator::ConnectServer method 

    IWbemServices *pSvc = NULL; 

    if (localconn) 
     hres = pLoc->ConnectServer(
      _bstr_t(strNetworkResource),  // Object path of WMI namespace 
      NULL,     // User name. NULL = current user 
      NULL,     // User password. NULL = current 
      0,      // Locale. NULL indicates current 
      NULL,     // Security flags. 
      0,      // Authority (e.g. Kerberos) 
      0,      // Context object 
      &pSvc     // pointer to IWbemServices proxy 
      ); 
    else 
     hres = pLoc->ConnectServer(
      _bstr_t(strNetworkResource), // Object path of WMI namespace 
      _bstr_t(pszName),    // User name 
      _bstr_t(pszPwd),    // User password 
      NULL,    // Locale 
      NULL,    // Security flags 
      NULL,    // Authority 
      NULL,    // Context object 
      &pSvc    // IWbemServices proxy 
      ); 

    if (FAILED(hres)) 
    { 
     cout << "Could not connect. Error code = 0x" << hex << hres << endl;  
     cout << _com_error(hres).ErrorMessage() << endl; 
     pLoc->Release(); 
     CoUninitialize(); 
     cout << "press enter to exit" << endl; 
     cin.get();   
     return 1;    // Program has failed. 
    } 

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

    // Set security levels on the proxy ------------------------- 
    if (localconn) 
     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 
     ); 
    else 
    { 
     // Create COAUTHIDENTITY that can be used for setting security on proxy 
     memset(&authIdent, 0, sizeof(COAUTHIDENTITY)); 
     authIdent.PasswordLength = wcslen (pszPwd); 
     authIdent.Password = (USHORT*)pszPwd; 
     authIdent.User = (USHORT*)pszName; 
     authIdent.UserLength = wcslen(pszName); 
     authIdent.Domain = 0; 
     authIdent.DomainLength = 0; 
     authIdent.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; 
     userAcct = &authIdent; 

     hres = CoSetProxyBlanket(
      pSvc,       // Indicates the proxy to set 
      RPC_C_AUTHN_DEFAULT,   // RPC_C_AUTHN_xxx 
      RPC_C_AUTHZ_DEFAULT,   // RPC_C_AUTHZ_xxx 
      COLE_DEFAULT_PRINCIPAL,   // Server principal name 
      RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx 
      RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx 
      userAcct,      // client identity 
      EOAC_NONE      // proxy capabilities 
     ); 
    } 

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

    // Use the IWbemServices pointer to make requests of WMI ---- 

    IEnumWbemClassObject* pEnumerator = NULL; 
    hres = pSvc->ExecQuery(L"WQL", L"SELECT * FROM Win32_NetworkAdapter", 
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator); 

    if (FAILED(hres)) 
    { 
     cout << "ExecQuery failed" << " Error code = 0x" << hex << hres << endl; 
     cout << _com_error(hres).ErrorMessage() << endl; 
     pSvc->Release(); 
     pLoc->Release(); 
     CoUninitialize(); 
     cout << "press enter to exit" << endl; 
     cin.get();  
     return 1;    // Program has failed. 
    } 

    // Secure the enumerator proxy 
    if (!localconn) 
    { 

     hres = CoSetProxyBlanket(
      pEnumerator,     // Indicates the proxy to set 
      RPC_C_AUTHN_DEFAULT,   // RPC_C_AUTHN_xxx 
      RPC_C_AUTHZ_DEFAULT,   // RPC_C_AUTHZ_xxx 
      COLE_DEFAULT_PRINCIPAL,   // Server principal name 
      RPC_C_AUTHN_LEVEL_PKT_PRIVACY, // RPC_C_AUTHN_LEVEL_xxx 
      RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx 
      userAcct,      // client identity 
      EOAC_NONE      // proxy capabilities 
      ); 

     if (FAILED(hres)) 
     { 
      cout << "Could not set proxy blanket on enumerator. Error code = 0x" << hex << hres << endl; 
      cout << _com_error(hres).ErrorMessage() << endl; 
      pEnumerator->Release(); 
      pSvc->Release(); 
      pLoc->Release(); 
      CoUninitialize(); 
      cout << "press enter to exit" << endl; 
      cin.get();    
      return 1;    // Program has failed. 
     } 
    } 

    // Get the data from the WQL sentence 
    IWbemClassObject *pclsObj = NULL; 
    ULONG uReturn = 0; 

    while (pEnumerator) 
    { 
     HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn); 

     if(0 == uReturn || FAILED(hr)) 
      break; 

     VARIANT vtProp; 

       hr = pclsObj->Get(L"AdapterType", 0, &vtProp, 0, 0);// String 
       if (!FAILED(hr)) 
       { 
        if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY)) 
        wcout << "AdapterType : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl; 
        else 
        wcout << "AdapterType : " << vtProp.bstrVal << endl; 
       } 
       VariantClear(&vtProp); 

       hr = pclsObj->Get(L"AdapterTypeId", 0, &vtProp, 0, 0);// Uint16 
       if (!FAILED(hr)) 
       { 
        if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY)) 
        wcout << "AdapterTypeId : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl; 
        else 
        wcout << "AdapterTypeId : " << vtProp.uiVal << endl; 
       } 
       VariantClear(&vtProp); 

       hr = pclsObj->Get(L"Caption", 0, &vtProp, 0, 0);// String 
       if (!FAILED(hr)) 
       { 
        if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY)) 
        wcout << "Caption : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl; 
        else 
        wcout << "Caption : " << vtProp.bstrVal << endl; 
       } 
       VariantClear(&vtProp); 

       hr = pclsObj->Get(L"Description", 0, &vtProp, 0, 0);// String 
       if (!FAILED(hr)) 
       { 
        if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY)) 
        wcout << "Description : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl; 
        else 
        wcout << "Description : " << vtProp.bstrVal << endl; 
       } 
       VariantClear(&vtProp); 

       hr = pclsObj->Get(L"MACAddress", 0, &vtProp, 0, 0);// String 
       if (!FAILED(hr)) 
       { 
        if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY)) 
        wcout << "MACAddress : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl; 
        else 
        wcout << "MACAddress : " << vtProp.bstrVal << endl; 
       } 
       VariantClear(&vtProp); 


     pclsObj->Release(); 
     pclsObj=NULL; 
    } 

    // Cleanup 

    pSvc->Release(); 
    pLoc->Release(); 
    pEnumerator->Release(); 
    if (pclsObj!=NULL) 
    pclsObj->Release(); 

    CoUninitialize(); 
    cout << "press enter to exit" << endl; 
    cin.get(); 
    return 0; // Program successfully completed. 
} 
0

쿼리는 IEnumWbemClassObject 인터페이스의 인스턴스를 반환합니다. 개체를 열거 할 때 사용할 수 있습니다. 객체는 IWbemClassObject 인스턴스로 반환됩니다. 그런 다음 IWbemClassObject::Get 메서드를 사용하여 속성을 가져올 수 있습니다.

See this MSDN sample; 그러나 일반적으로 원시 인터페이스 포인터 대신 CComPtr<> ATL 클래스를 사용합니다. CComVariantVARIANT과 동일합니다.

+0

파일에 값을 인쇄하려고 내가 Win32_NetworkAdapter.I의 설명 멤버에 접근하고 말할 수 있습니다 응용 프로그램에 의해 생성이 샘플 코드를 사용해보십시오. 콘솔에서 인쇄 할 때 문제가 없지만 파일에 이해할 수없는 값이 기록됩니다. 스 니펫이나 다른 것을 알려주시겠습니까? – user3194643

+0

VARIANT vtProp; \t \t \t \t \t \t \t \t \t \t \t \t HR = pclsObj-> 길 (L "이름", 0, vtProp, 0, 0); \t \t \t \t wcout << "Name :"<< vtProp. bstrVal << "\ t \ t"; \t \t \t \t \t \t \t \t HR = pclsObj-> 길 (L "DriverVersion", 0, vtProp, 0, 0); \t \t \t \t wcout << "DriverVersion :"<< vtProp.bstrVal << endl; \t \t \t \t VariantClear (& vtProp); 이것은 나를 사용하는 코드입니다. 왜 우리는 vtProp.bstrVal을 사용해야하고 변형의 다른 멤버는 사용하지 않아야하는지 이해하지 못합니다. 무엇을 사용해야합니까? – user3194643

+0

MSDN에서 전체 샘플을 제공했습니다. bstrVal 정보 - 그 이유는 다음과 같습니다. http://msdn.microsoft.com/en-us/library/windows/desktop/ms221627(v=vs.85).aspx – Soonts