Error 0x8004100e connecting to WMI namespace - c++

I'm using Windows 7 and now I want to develop a program with WMI.
I've read MSDN and found this example code.
#include "stdafx.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
#include <conio.h>
# pragma comment(lib, "wbemuuid.lib")
BOOL ManageWMI();
int main(int argc, char* argv[])
{
if(ManageWMI()) printf("%WMI Error!");
_getch();
return 0;
}
BOOL ManageWMI()
{
HRESULT hres;
// Step 1: --------------------------------------------------
// 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.
}
cout << "step 1" << endl;
// Step 2: --------------------------------------------------
// Set general COM security levels --------------------------
// Note: If you are using Windows 2000, you need to specify -
// the default authentication credentials for a user by using
// a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
// parameter of CoInitializeSecurity ------------------------
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 (FAILED(hres))
{
cout << "Failed to initialize security. Error code = 0x"
<< hex << hres << endl;
CoUninitialize();
return 1; // Program has failed.
}
cout << "step 2 " << endl;
// 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))
{
cout << "Failed to create IWbemLocator object."
<< " Err code = 0x"
<< hex << hres << endl;
CoUninitialize();
return 1; // Program has failed.
}
cout << "step 3" << endl;
// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = 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 (e.g. Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x"
<< hex << hres << endl;
pLoc->Release();
cout << "released!!" << endl;
CoUninitialize();
cout << "counitialized !!" << endl;
return 1; // Program has failed.
}
cout<< "step 4" << endl;
cout << "Connected to ROOT//CIMV2 WMI namespace" << endl;
// Step 5: --------------------------------------------------
// Set security levels on the proxy -------------------------
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
);
cout << "step 5" << endl;
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.
}
// Step 6: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----
// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = ''TRUE''"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hres))
{
cout << "Query for Network Adapter Configuration failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1; // Program has failed.
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
IWbemClassObject *pclsObj;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn)
{
break;
}
VARIANT vtProp;
VariantInit(&vtProp);
//hr = pclsObj->Get(L"IPSubnet", 0, &vtProp, 0, 0);
// Get the value of the Enable property
hr = pclsObj->Get(L"IPEnabled", 0, &vtProp, 0, 0);
// Get the value of the MacAddress property
if(vtProp.boolVal)
{
hr = pclsObj->Get(L"MacAddress", 0, &vtProp, 0, 0);
wcout << " MacAddress : " << vtProp.bstrVal << endl;
}
hr = pclsObj->Get(L"IPEnabled", 0, &vtProp, 0, 0);
if(vtProp.boolVal)
{
LONG lstart, lend;
LONG idx = -1;
BSTR* pbstr;
SAFEARRAY *sa;
hr = pclsObj->Get(L"Description", 0, &vtProp, 0, 0);
if(!FAILED(hr))
{
wcout << "Description: " << vtProp.bstrVal << endl;
}
hr = pclsObj->Get(L"DNSHostName", 0, &vtProp, 0, 0);
if(!FAILED(hr))
{
cout << "DNS:" << vtProp.bstrVal << endl;
}
hr = pclsObj->Get(L"IPAddress", 0, &vtProp, 0, 0);
if(!FAILED(hr))
{
SAFEARRAY *psa = vtProp.parray;
cout << "IP Address::" << psa << endl;
}
}
VariantClear(&vtProp);
}
// Cleanup
// ========
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
pclsObj->Release();
CoUninitialize();
return 0; // Program successfully completed.
}
However, these code doesn't work on my computer.
It failed in "step4" with error code 0x8004100e.
I googled and restart my WMI service but doesn't work either.
Does anyone had the same experience and solved that? Hope you give me some help. Thanks...

You are using a wrong syntax for the ROOT//CIMV2 namespace try changing to ROOT\\CIMV2
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 (e.g. Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
Btw the 0x8004100E value is the code for the WBEM_E_INVALID_NAMESPACE (Namespace specified cannot be found.) error.

Related

How to query for VM features using WMI class Msvm_SummaryInformation or Msvm_VirtualSystemManagementService in C++

This is code snippet from MSFT documentation
https://learn.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer
The example uses Win32_OperatingSystem and it works fine. I replaced Win32_OperatingSystem with Msvm_SummaryInformation or Msvm_VirtualSystemManagementService
now uReturn returns 0. I tried lot of things none seemed to work
Please help me out or point me to a C++ program using Msvm_SummaryInformation
// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Msvm_SummaryInformation"), // Win32_OperatingSystem
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hres))
{
cout << "Query for operating system name failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1; // Program has failed.
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
&pclsObj, &uReturn);
if(0 == uReturn) // ==> This returns 0
{
break;
}
Finally after some struggle I got it fully working and here is the working code:
This produces VM - GUID, Name and State. One can use Msvm_SummaryInformation or Msvm_ComputerSystem I prefer Msvm_SummaryInformation as that Class has more detailed info. I used the example and built on it. No more PS for me :)
/*
https://learn.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer
*/#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;
// Step 1: --------------------------------------------------
// 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.
}
// 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 (FAILED(hres))
{
cout << "Failed to initialize security. Error code = 0x"
<< hex << hres << endl;
CoUninitialize();
return 1; // Program has failed.
}
// 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))
{
cout << "Failed to create IWbemLocator object."
<< " Err code = 0x"
<< hex << hres << endl;
CoUninitialize();
return 1; // Program has failed.
}
// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method
IWbemServices *pSvc = NULL;
// Connect to the root\cimv2 namespace with
// the current user and obtain pointer pSvc
// to make IWbemServices calls.
// L"ROOT\\CIMV2" for Win32_OperatingSystem
// L"ROOT\\Virtualization\\V2" for Msvm_SummaryInformation
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\Virtualization\\V2"), // Object path of WMI namespace
//_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
&pSvc // pointer to 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;
cout << "Connected to ROOT\\Virtualization V2 WMI namespace" << endl;
// Step 5: --------------------------------------------------
// Set security levels on the proxy -------------------------
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
);
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.
}
// Step 6: --------------------------------------------------
// Use the IWbemServices pointer to make requests of WMI ----
// For example, get the name of the operating system
IEnumWbemClassObject* pEnumerator = NULL;
hres = pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM Msvm_SummaryInformation"),
//bstr_t("SELECT * FROM Msvm_ComputerSystem where Caption=\"Virtual Machine\""),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);
if (FAILED(hres))
{
cout << "Query for operating system name failed."
<< " Error code = 0x"
<< hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 1; // Program has failed.
}
// Step 7: -------------------------------------------------
// Get the data from the query in step 6 -------------------
IWbemClassObject *pclsObj = NULL;
ULONG uReturn = 0;
while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(
WBEM_INFINITE,
1,
&pclsObj,
&uReturn);
if(0 == uReturn)
{
break;
}
VARIANT vtProp;
// Get the value of the Name property
hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
if (vtProp.vt != VT_NULL) {
wcout << " VM GUID : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"ElementName", 0, &vtProp, 0, 0);
if (vtProp.vt != VT_NULL) {
wcout << " VM Name : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"PrimaryOwnerName", 0, &vtProp, 0, 0);
if (vtProp.vt != VT_NULL) {
wcout << " PrimaryOwnerName : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"EnabledState", 0, &vtProp, 0, 0);
if (vtProp.vt != VT_NULL) {
wcout << " EnabledState : " << vtProp.ulVal << endl;
}
VariantClear(&vtProp);
pclsObj->Release();
}
// Cleanup
// ========
pSvc->Release();
pLoc->Release();
pEnumerator->Release();
CoUninitialize();
return 0; // Program successfully completed.
}

WMI SoftwareLicensingProduct class doesn't show Partial Product Key for MS Office on some systems ( Windows 10)

Using WMI SoftwareLicensingProduct class I am fetching Partial Product Key / License Key for Microsoft Product.
Its compatible with Windows Vista and above.
But still I am not able to retrieve the Key for MS Office on few Windows10 system, for rest of the systems, its working as expected.
Code :
int _tmain(int argc, _TCHAR* 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 SoftwareLicensingProduct"),
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 << " ";
VariantClear(&vtProp);
VARIANT vtProp1;
// Get the value of the PartialProductKey property
hres = pclsObj->Get(L"PartialProductKey", 0, &vtProp1, 0, 0);
if (VT_NULL != vtProp1.vt)
wcout << ": " << vtProp1.bstrVal << endl;
else
wcout<<endl;
VariantClear(&vtProp1);
}
}
getch();
// Cleanup
// ========
pSvc->Release();
pLoc->Release();
CoUninitialize();
return 0; // Program successfully completed.
}

How can I find out the command line arguments of a running application? [duplicate]

How do I get the command line arguments of all running processes in Windows using WMI in the C language?
You must use the Win32_Process WMI class and check the value of the CommandLine property, also take a look to this article How do I get the command line of another process which explains that string is ...just "preinitialized variable", a process could in principle (and many do in practice, although usually inadvertently) write to the memory that holds the command line
Update
C Sample
#define _WIN32_WINNT 0x0400
#define _WIN32_DCOM
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <wbemidl.h>
void _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = 0;
IWbemLocator *WbemLocator = NULL;
IWbemServices *WbemServices = NULL;
IEnumWbemClassObject *EnumWbem = NULL;
//initializate the Windows security
hr = CoInitializeEx(0, COINIT_MULTITHREADED);
hr = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
hr = CoCreateInstance(&CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, &IID_IWbemLocator, (LPVOID *) &WbemLocator);
//connect to the WMI
hr = WbemLocator->lpVtbl->ConnectServer(WbemLocator, L"ROOT\\CIMV2", NULL, NULL, NULL, 0, NULL, NULL, &WbemServices);
//Run the WQL Query
hr = WbemServices->lpVtbl->ExecQuery(WbemServices, L"WQL", L"SELECT ProcessId,CommandLine FROM Win32_Process", WBEM_FLAG_FORWARD_ONLY, NULL, &EnumWbem);
// Iterate over the enumerator
if (EnumWbem != NULL) {
IWbemClassObject *result = NULL;
ULONG returnedCount = 0;
while((hr = EnumWbem->lpVtbl->Next(EnumWbem, WBEM_INFINITE, 1, &result, &returnedCount)) == S_OK) {
VARIANT ProcessId;
VARIANT CommandLine;
// access the properties
hr = result->lpVtbl->Get(result, L"ProcessId", 0, &ProcessId, 0, 0);
hr = result->lpVtbl->Get(result, L"CommandLine", 0, &CommandLine, 0, 0);
if (!(CommandLine.vt==VT_NULL))
wprintf(L"%u %s \r\n", ProcessId.uintVal, CommandLine.bstrVal);
result->lpVtbl->Release(result);
}
}
// Release the resources
EnumWbem->lpVtbl->Release(EnumWbem);
WbemServices->lpVtbl->Release(WbemServices);
WbemLocator->lpVtbl->Release(WbemLocator);
CoUninitialize();
getchar();
}
Borland C++ Sample
#pragma hdrstop
#include <iostream>
using namespace std;
#include <wbemcli.h>
#include <comdef.h>
//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)
// The Win32_Process class represents a sequence of events on a Win32 system. Any sequence consisting of the interaction of one or more processors or interpreters, some executable code, and a set of inputs, is a descendent (or member) of this class.
// Example: A client application running on a Win32 system.
#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(
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(
strNetworkResource, // Object path of WMI namespace
pszName, // User name
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 CommandLine,ProcessId FROM Win32_Process",
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"CommandLine", 0, &vtProp, 0, 0);// String
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "CommandLine : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
if ((vtProp.vt & VT_ARRAY))
wcout << "CommandLine : " << "Array types not supported (yet)" << endl;
else
wcout << "CommandLine : " << vtProp.bstrVal << endl;
}
VariantClear(&vtProp);
hr = pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);// Uint32
if (!FAILED(hr))
{
if ((vtProp.vt==VT_NULL) || (vtProp.vt==VT_EMPTY))
wcout << "ProcessId : " << ((vtProp.vt==VT_NULL) ? "NULL" : "EMPTY") << endl;
else
if ((vtProp.vt & VT_ARRAY))
wcout << "ProcessId : " << "Array types not supported (yet)" << endl;
else
wcout << "ProcessId : " << vtProp.uintVal << 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.
}

Calling Chkdsk from WMI (Win32_LogicalDisk class) in C++ -> 'Parameter is not valid'

I'm trying to run Chkdsk from WMI in C++ (I'm using Qt Framework). 'ExecMethod' returns 'Parameter is not valid'.
I've set parameters according to http://msdn.microsoft.com/en-us/library/cc250766.aspx
-> I'm using semisynchronously call.
I'm using MSDN Documentation (Win32_LogicalDisk, WMI C++ Application Examples, Win32_Volume,...)
I was also trying with Win32_Volume but it wasn't working as well.
Part of my code:
IWbemLocator *pLoc = NULL;
HRESULT hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc);
IWbemServices *pSvc = NULL;
hres = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
BSTR MethodName = SysAllocString(L"Chkdsk");
BSTR ClassName = SysAllocString(L"Win32_LogicalDisk");
IWbemCallResult *pCallRes = 0;
hres = pSvc->ExecMethod(ClassName, MethodName, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, NULL, NULL, &pCallRes);
I've also tried with:
BSTR ClassName = SysAllocString(L"Win32_LogicalDisk.DeviceID='C:'");
but there is this same problem.
Any help would be welcome.
You are not passing a proper value to the classname parameter
You must use something like L"Win32_LogicalDisk.DeviceID=\"C:\""
Anyway this is a full sample console app.
#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;
HRESULT hres;
// Initialize COM. ------------------------------------------
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;
// Connect to the root\\CIMV2 namespace
// and obtain pointer pSvc to make IWbemServices calls.
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 ----
BSTR MethodName = SysAllocString(L"Chkdsk");
BSTR ClassName = SysAllocString(L"Win32_LogicalDisk");
IWbemClassObject* pClass = NULL;
hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
IWbemClassObject* pInParamsDefinition = NULL;
hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);
IWbemClassObject* pClassInstance = NULL;
hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);
VARIANT varCommand;
// Execute Method
IWbemClassObject* pOutParams = NULL;
hres = pSvc->ExecMethod(L"Win32_LogicalDisk.DeviceID=\"C:\"", MethodName, 0,
NULL, pClassInstance, &pOutParams, NULL);
if (FAILED(hres))
{
cout << "Could not execute method. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
SysFreeString(ClassName);
SysFreeString(MethodName);
if (pClass) pClass->Release();
if (pInParamsDefinition) pInParamsDefinition->Release();
if (pOutParams) pOutParams->Release();
if (pSvc) pSvc->Release();
if (pLoc) pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
VARIANT varReturnValue;
hres = pOutParams->Get(L"ReturnValue", 0, &varReturnValue, NULL, 0);
if (!FAILED(hres))
wcout << "ReturnValue " << varReturnValue.intVal << endl;
VariantClear(&varReturnValue);
// Clean up
SysFreeString(ClassName);
SysFreeString(MethodName);
if (pClass) pClass->Release();
if (pInParamsDefinition) pInParamsDefinition->Release();
if (pOutParams) pOutParams->Release();
if (pLoc) pLoc->Release();
if (pSvc) pSvc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0;
}
If you are new to the WMI and C++, you can try a tool like the WMI Delphi Code Creator which can help you to create C++ code to access the WMI.

How do I use C to terminate a process on a remote computer?

Platform: Windows
Language: C/C++
I need a way to terminate a process on a remote computer, it is a remote service actually which is unresponsive to the SERVICE_STOP command, does anyone know how would I go about doing that?
For kill a process in a remote machine you can use the Win32_Process WMI class and the Terminate method and for stop a remote service you can use the Win32_Service and the StopService method.
Here is a C++ sample:
#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)
// The Terminate method terminates a process and all of its threads. The method returns an integer value that can be interpretted as follows:
// 0 - Successful completion.
// 2 - The user does not have access to the requested information.
// 3 - The user does not have sufficient privilge.
// 8 - Unknown failure.
// 9 - The path specified does not exist.
// 21 - The specified parameter is invalid.
// Other - For integer values other than those listed above, refer to Win32 error code documentation.
//
// Note: The SE_DEBUG_PRIVILEGE privilege is required to invoke this method
#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;
HRESULT hres;
// Initialize COM. ------------------------------------------
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;
// Connect to the root\\CIMV2 namespace
// and obtain pointer pSvc to make IWbemServices calls.
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 ----
BSTR MethodName = SysAllocString(L"Terminate");
BSTR ClassName = SysAllocString(L"Win32_Process");
IWbemClassObject* pClass = NULL;
hres = pSvc->GetObject(ClassName, 0, NULL, &pClass, NULL);
IWbemClassObject* pInParamsDefinition = NULL;
hres = pClass->GetMethod(MethodName, 0, &pInParamsDefinition, NULL);
IWbemClassObject* pClassInstance = NULL;
hres = pInParamsDefinition->SpawnInstance(0, &pClassInstance);
VARIANT varCommand;
// Execute Method
IWbemClassObject* pOutParams = NULL;
// Pass the Pid of the process to terminate
hres = pSvc->ExecMethod(L"Win32_Process.Handle=\"4532\"", MethodName, 0,
NULL, pClassInstance, &pOutParams, NULL);
if (FAILED(hres))
{
cout << "Could not execute method. Error code = 0x" << hex << hres << endl;
cout << _com_error(hres).ErrorMessage() << endl;
SysFreeString(ClassName);
SysFreeString(MethodName);
if (pClass) pClass->Release();
if (pInParamsDefinition) pInParamsDefinition->Release();
if (pOutParams) pOutParams->Release();
if (pSvc) pSvc->Release();
if (pLoc) pLoc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 1; // Program has failed.
}
VARIANT varReturnValue;
hres = pOutParams->Get(L"ReturnValue", 0, &varReturnValue, NULL, 0);
if (!FAILED(hres))
wcout << "ReturnValue " << varReturnValue.intVal << endl;
VariantClear(&varReturnValue);
// Clean up
SysFreeString(ClassName);
SysFreeString(MethodName);
if (pClass) pClass->Release();
if (pInParamsDefinition) pInParamsDefinition->Release();
if (pOutParams) pOutParams->Release();
if (pLoc) pLoc->Release();
if (pSvc) pSvc->Release();
CoUninitialize();
cout << "press enter to exit" << endl;
cin.get();
return 0;
}