簡體   English   中英

WMI ConnectServer到ROOT \\ CIMV2對於C ++應用程序返回“訪問被拒絕”,但對於C#應用程序工作正常

[英]WMI ConnectServer to ROOT\CIMV2 returns 'Access Denied' for C++ Application but works fine for C# Application

我下面這個文章來查詢WMI。 目的是通過使用查詢Select * from Win32_Process獲得正在運行的進程的詳細信息,查詢成功后,將遍歷結果。 但是在調用pLoc->ConnectServer(_bstr_t(L"\\\\ROOT\\\\CIMV2"), NULL, NULL,0,NULL,0,0,&pSvc); ,我得到HRESULT_FROM_WIN32(ERROR_SERVICE_DOES_NOT_EXIST) : The specified service does not exist as an installed service. 我已經在compmgmt.msc檢查了WMI Control的權限,這似乎很好。 我試圖以管理員身份運行該應用程序,但結果相同。

編輯代碼

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.

}

我在C#中也有類似的代碼庫。 我正在使用ObjectQuery形成sql查詢,並使用ManagementObjectSearcher來獲取結果。 我使用的查詢略有不同Select * from Win32_Process Where ProcessID = '" + PID + "' 通過對Process.GetProcesses()的結果進行迭代來傳遞PID。 這個C#應用程序工作正常,我能夠看到所有正在運行的進程的詳細信息。

編輯代碼

 ObjectQuery sq = new ObjectQuery
             ("Select * from Win32_Process Where ProcessID = '" + PID + "'");

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, sq);
            if (searcher == null)
            {
                Console.WriteLine("Searcher is empty...returning");
                return String.Empty;
            }
            if (searcher.Get().Count == 0)
                return OwnerSID;
            foreach (ManagementObject oReturn in searcher.Get())
            {
                using (ManagementObjectCollection oReturnC = searcher.Get())
                {
                    FullPath = (from mo in oReturnC.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();
                    CommandLine = (from mo in oReturnC.Cast<ManagementObject>() select mo["CommandLine"]).First().ToString();
                    parentprocessid = (from mo in oReturnC.Cast<ManagementObject>() select mo["ParentProcessId"]).First().ToString();
                    ppid = Convert.ToInt32(parentprocessid);
                    Process parentProcess = Process.GetProcessById(ppid);
                    ppname = parentProcess.ProcessName;
                }

            }

另一個奇怪的現象,我發現是,當我從應用程序中更改C#的DLL,並在下面的C ++應用程序(遺留原因)使用此DLL ,我得到了同樣的錯誤- The specified service does not exist as an installed service

我已經在Google上搜索了很多,找不到任何解決此問題的方法。 有什么原因使C#能夠訪問WMI而不是C ++。

下頁指示在連接到本地系統時不要使用前導\\: https : //docs.microsoft.com/zh-cn/windows/desktop/wmisdk/creating-a-connection-to-a-wmi-namespace

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM