pilus87

WMI Query C++

Sep 11th, 2011
423
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 9.83 KB | None | 0 0
  1. //From: http://msdn.microsoft.com/en-us/library/aa394175(v=vs.85).aspx
  2.  
  3. #define _WIN32_DCOM
  4. #include <iostream>
  5. using namespace std;
  6. #include <comdef.h>
  7. #include <Wbemidl.h>
  8. #pragma comment(lib, "wbemuuid.lib")
  9.  
  10. BOOL wmi_run();
  11. BOOL wmi_getDriveLetters();
  12. BOOL wmi_close();
  13.  
  14. IWbemLocator *pLoc = NULL;
  15. IWbemServices *pSvc = NULL;
  16.  
  17. int main(int argc, char **argv)
  18. {
  19.     wmi_run();
  20.     wmi_getDriveLetters();
  21.     system("pause");
  22.     wmi_close();
  23. }
  24.  
  25. //
  26. // Step 1-5 at:
  27. // http://msdn.microsoft.com/en-us/library/aa390423(VS.85).aspx
  28. BOOL wmi_run()
  29. {
  30.      HRESULT hres;
  31.     // Step 1: --------------------------------------------------
  32.     // Initialize COM. ------------------------------------------
  33.     hres =  CoInitializeEx(0, COINIT_MULTITHREADED);
  34.     if (FAILED(hres))
  35.     {
  36.         cout << "Failed to initialize COM library. Error code = 0x"
  37.             << hex << hres << endl;
  38.         return 1;                  // Program has failed.
  39.     }
  40.     // Step 2: --------------------------------------------------
  41.     // Set general COM security levels --------------------------
  42.     // Note: If you are using Windows 2000, you need to specify -
  43.     // the default authentication credentials for a user by using
  44.     // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
  45.     // parameter of CoInitializeSecurity ------------------------
  46.     hres =  CoInitializeSecurity(
  47.         NULL,
  48.         -1,                          // COM authentication
  49.         NULL,                        // Authentication services
  50.         NULL,                        // Reserved
  51.         RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication
  52.         RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
  53.         NULL,                        // Authentication info
  54.         EOAC_NONE,                   // Additional capabilities
  55.         NULL                         // Reserved
  56.         );
  57.  
  58.     if (FAILED(hres))
  59.     {
  60.         cout << "Failed to initialize security. Error code = 0x"
  61.             << hex << hres << endl;
  62.         CoUninitialize();
  63.         return 1;                    // Program has failed.
  64.     }
  65.  
  66.     // Step 3: ---------------------------------------------------
  67.     // Obtain the initial locator to WMI -------------------------
  68.     //IWbemLocator *pLoc = NULL;
  69.     hres = CoCreateInstance(
  70.         CLSID_WbemLocator,            
  71.         0,
  72.         CLSCTX_INPROC_SERVER,
  73.         IID_IWbemLocator, (LPVOID *) &pLoc);
  74.  
  75.     if (FAILED(hres))
  76.     {
  77.         cout << "Failed to create IWbemLocator object."
  78.             << " Err code = 0x"
  79.             << hex << hres << endl;
  80.         CoUninitialize();
  81.         return 1;                 // Program has failed.
  82.     }
  83.     // Step 4: -----------------------------------------------------
  84.     // Connect to WMI through the IWbemLocator::ConnectServer method
  85.     //IWbemServices *pSvc = NULL;
  86.  
  87.     // Connect to the root\cimv2 namespace with
  88.     // the current user and obtain pointer pSvc
  89.     // to make IWbemServices calls.
  90.     hres = pLoc->ConnectServer(
  91.          _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace
  92.          NULL,                    // User name. NULL = current user
  93.          NULL,                    // User password. NULL = current
  94.          0,                       // Locale. NULL indicates current
  95.          NULL,                    // Security flags.
  96.          0,                       // Authority (e.g. Kerberos)
  97.          0,                       // Context object
  98.          &pSvc                    // pointer to IWbemServices proxy
  99.          );
  100.  
  101.     if (FAILED(hres))
  102.     {
  103.         cout << "Could not connect. Error code = 0x"
  104.              << hex << hres << endl;
  105.         pLoc->Release();    
  106.         CoUninitialize();
  107.         return 1;                // Program has failed.
  108.     }
  109.     cout << "Connected to ROOT\\CIMV2 WMI namespace" << endl;
  110.     // Step 5: --------------------------------------------------
  111.     // Set security levels on the proxy -------------------------
  112.     hres = CoSetProxyBlanket(
  113.        pSvc,                        // Indicates the proxy to set
  114.        RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx
  115.        RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx
  116.        NULL,                        // Server principal name
  117.        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx
  118.        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
  119.        NULL,                        // client identity
  120.        EOAC_NONE                    // proxy capabilities
  121.     );
  122.     if (FAILED(hres))
  123.     {
  124.         cout << "Could not set proxy blanket. Error code = 0x"
  125.             << hex << hres << endl;
  126.         pSvc->Release();
  127.         pLoc->Release();    
  128.         CoUninitialize();
  129.         return 1;               // Program has failed.
  130.     }
  131.  return 0;
  132. }
  133.  
  134. //
  135. // get Drives, logical Drives and Driveletters
  136. BOOL wmi_getDriveLetters()
  137. {
  138.     // Use the IWbemServices pointer to make requests of WMI.
  139.     // Make requests here:
  140.     HRESULT hres;
  141.     IEnumWbemClassObject* pEnumerator = NULL;
  142.     // get localdrives
  143.     hres = pSvc->ExecQuery(
  144.                     bstr_t("WQL"),
  145.                     bstr_t("SELECT * FROM Win32_DiskDrive"),
  146.                     WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
  147.                     NULL,
  148.                     &pEnumerator);
  149.  
  150.     if (FAILED(hres)) {
  151.         cout << "Query for processes failed. "
  152.              << "Error code = 0x"
  153.              << hex << hres << endl;
  154.         pSvc->Release();
  155.         pLoc->Release();    
  156.         CoUninitialize();
  157.         return FALSE;               // Program has failed.
  158.     }
  159.     else {
  160.         IWbemClassObject *pclsObj;
  161.         ULONG uReturn = 0;
  162.         while (pEnumerator) {
  163.            hres = pEnumerator->Next(WBEM_INFINITE, 1,
  164.                                  &pclsObj, &uReturn);
  165.            if(0 == uReturn) break;
  166.            VARIANT vtProp;
  167.            hres = pclsObj->Get(_bstr_t(L"DeviceID"), 0, &vtProp, 0, 0);
  168.            // adjust string
  169.            wstring tmp = vtProp.bstrVal;
  170.            tmp = tmp.substr(4);
  171.  
  172.            wstring wstrQuery = L"Associators of {Win32_DiskDrive.DeviceID='\\\\.\\";
  173.            wstrQuery += tmp;
  174.            wstrQuery += L"'} where AssocClass=Win32_DiskDriveToDiskPartition";
  175.            // reference drive to partition
  176.            IEnumWbemClassObject* pEnumerator1 = NULL;
  177.            hres = pSvc->ExecQuery(
  178.                              bstr_t("WQL"),
  179.                              bstr_t( wstrQuery.c_str()),
  180.                              WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
  181.                              NULL,
  182.                              &pEnumerator1 );
  183.  
  184.            if ( FAILED(hres) ) {
  185.             cout << "Query for processes failed. "
  186.                           << "Error code = 0x"
  187.                           << hex << hres << endl;
  188.             pSvc->Release();
  189.             pLoc->Release();    
  190.             CoUninitialize();
  191.             return FALSE;               // Program has failed.
  192.            } else {
  193.  
  194.                 IWbemClassObject *pclsObj1;
  195.                 ULONG uReturn1 = 0;
  196.                 while( pEnumerator1 ) {
  197.                      hres = pEnumerator1->Next( WBEM_INFINITE, 1,
  198.                      &pclsObj1, &uReturn1 );
  199.                      if(0 == uReturn1) break;
  200.                      // reference logical drive to partition
  201.                      VARIANT vtProp1;
  202.                      hres = pclsObj1->Get( _bstr_t(L"DeviceID"), 0, &vtProp1, 0, 0 );
  203.                      wstring wstrQuery = L"Associators of {Win32_DiskPartition.DeviceID='";
  204.                      wstrQuery += vtProp1.bstrVal;
  205.                      wstrQuery += L"'} where AssocClass=Win32_LogicalDiskToPartition";
  206.  
  207.                      IEnumWbemClassObject* pEnumerator2 = NULL;
  208.                      hres = pSvc->ExecQuery(
  209.                                        bstr_t("WQL"),
  210.                                        bstr_t(wstrQuery.c_str()),
  211.                                        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
  212.                                        NULL,
  213.                                        &pEnumerator2 );
  214.  
  215.  
  216.  
  217.  
  218.  
  219.                     if ( FAILED(hres) ) {
  220.                         cout << "Query for processes failed. "
  221.                                 << "Error code = 0x"
  222.                                 << hex << hres << endl;
  223.                         pSvc->Release();
  224.                         pLoc->Release();    
  225.                         CoUninitialize();
  226.                         return FALSE;               // Program has failed.
  227.                      } else {
  228.  
  229.                         // get driveletter
  230.                         IWbemClassObject *pclsObj2;
  231.                         ULONG uReturn2 = 0;
  232.                         while( pEnumerator2 ) {
  233.                             hres = pEnumerator2->Next( WBEM_INFINITE, 1,
  234.                             &pclsObj2, &uReturn2 );
  235.                             if(0 == uReturn2) break;
  236.                             VARIANT vtProp2;
  237.                             hres = pclsObj2->Get( _bstr_t(L"DeviceID"), 0, &vtProp2, 0, 0 );
  238.  
  239.                             // print result
  240.                             printf("%ls : %ls\n", vtProp.bstrVal, vtProp2.bstrVal);
  241.                             VariantClear( &vtProp2 );
  242.                         }
  243.                         pclsObj1->Release();
  244.                     }
  245.                     VariantClear( &vtProp1 );
  246.                     pEnumerator2->Release();
  247.                 }
  248.                 pclsObj->Release();
  249.             }
  250.             VariantClear( &vtProp );
  251.             pEnumerator1->Release();
  252.         }
  253.      }
  254.      pEnumerator->Release();
  255.      return TRUE;
  256. }
  257.  
  258.  
  259.  
  260. BOOL wmi_close()
  261. {
  262.  // Cleanup
  263.     // ========
  264.  
  265.     pSvc->Release();
  266.     pLoc->Release();
  267.     CoUninitialize();
  268.     return 0;   // Program successfully completed.
  269. }
Advertisement
Add Comment
Please, Sign In to add comment