C++对WMI的COM调用

需求

需要对某个网卡进行配置,比如设置DNS、IP地址或者WINS Server。前两个可以分别用注册表和CreateUnicastIpAddressEntry来做。但是后面那个,根本找不到对应的API。搜索了半天,发现要么是C#的示例,要么是PowerShell的示例,唯独没有C++示例。就算是有C++示例,最多也是查询的,没有设置的。我对COM组件的使用并不是很熟悉,感觉用起来很麻烦。后面又搜索了半天,如何调用Object中的函数。终于找到了方法,直接上代码

示例代码

目标

  • 设置某一个Network Adapter的WINS Server

参考链接

  1. SetWINSServer 微软文档
  2. Calling Instance Methods in WMI 只有代码片段,有些指针不知从何而来
  3. Using WMI to call method on objects 完整的代码,但并没有如何调用带参数的函数的方法
  4. 2 和 3 结合起来,我就写出能用的代码了,不容易~~

代码

#include 
#include 
#include 
#include 
#include 
#include 

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

int main(int argc, char * argv[]) {

    HRESULT hres;

    // Step 1: --------------------------------------------------
    // Initialize COM. ------------------------------------------

    do {
        hres = CoInitializeEx(0, COINIT_MULTITHREADED);
        if (FAILED(hres)) {
            break;
        }

        // Step 2: --------------------------------------------------
        // Set general COM security levels --------------------------

        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 (hres != S_OK && hres != RPC_E_TOO_LATE) {
            break;
        }

        // Step 3: ---------------------------------------------------
        // Obtain the initial locator to WMI -------------------------

        IWbemLocator *pLoc = NULL;

        hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc);

        if (FAILED(hres)) {
            CoUninitialize();
            break;
        }

        // Step 4: -----------------------------------------------------
        // Connect to WMI through the IWbemLocator::ConnectServer method

        IWbemServices *pService = NULL;

        // 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"), // 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 (for example, Kerberos)
            0,                       // Context object 
            &pService                    // pointer to IWbemServices proxy
        );

        if (FAILED(hres)) {
            pLoc->Release();
            CoUninitialize();
            break;
        }

        // Step 5: --------------------------------------------------
        // Set security levels on the proxy -------------------------

        hres = CoSetProxyBlanket(
            pService,                        // 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)) {
            pService->Release();
            pLoc->Release();
            CoUninitialize();
            break;               // Program has failed.
        }

        // Step 6: --------------------------------------------------
        // Use the IWbemServices pointer to make requests of WMI ----

        // For example, get the name of the operating system
        IEnumWbemClassObject* pEnumerator = NULL;
        hres = pService->ExecQuery(
            bstr_t("WQL"),
            bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE index = 1"),
            WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
            NULL,
            &pEnumerator);

        if (FAILED(hres)) {
            pService->Release();
            pLoc->Release();
            CoUninitialize();
            break; // Program has failed.
        }

        // Step 7: -------------------------------------------------
        // Get the data from the query in step 6 -------------------

        IWbemClassObject *config = NULL;
        IWbemClassObject *pclsObj = NULL;
        IWbemClassObject *params = NULL;
        IWbemClassObject *paramsInst = NULL;
        ULONG uReturn = 0;

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

            pService->GetObject(_bstr_t(L"Win32_NetworkAdapterConfiguration"), 0, NULL, &config, NULL);
            config->GetMethod(_bstr_t("SetWINSServer"), 0, ¶ms, NULL);
            //pclsObj->GetMethod(_bstr_t(L"SetWINSServer"), 0, ¶ms, NULL);
            params->SpawnInstance(0, ¶msInst);

            _bstr_t paramValue1(L"8.8.8.8");
            _bstr_t paramValue2(L"6.6.6.6");
            VARIANT paramVt;
            paramVt.vt = VT_BSTR;
            paramVt.bstrVal = paramValue1;
            paramsInst->Put(L"WINSPrimaryServer", 0, ¶mVt, NULL);
            paramVt.bstrVal = paramValue2;
            paramsInst->Put(L"WINSSecondaryServer", 0, ¶mVt, NULL);

            VARIANT vtPath;
            VariantInit(&vtPath);
            pclsObj->Get(L"__PATH", 0, &vtPath, NULL, NULL);

            // Execute the SetWINSServer method on our object instance
            IWbemClassObject *results = NULL;
            if (!FAILED(pService->ExecMethod(vtPath.bstrVal, _bstr_t(L"SetWINSServer"), 0, NULL, paramsInst, &results, NULL))) {
                VARIANT vtRet;
                VariantInit(&vtRet);
                if (!FAILED(results->Get(L"ReturnValue", 0, &vtRet, NULL, 0))) {
                    printf("%d\n", vtRet.uintVal);
                }
                VariantClear(&vtRet);
                results->Release();
            }
            pclsObj->Release();
        }
        pService->Release();
        pLoc->Release();
        pEnumerator->Release();
        CoUninitialize();
    } while (false);
    return 0;
}

打完收工

你可能感兴趣的:(C++对WMI的COM调用)