Beispiel #1
1
// (Usually internal) method to perform usb drive search
bool DeviceFinder::MappingUsbstorToDeviceNumber(std::map<std::string, int>& usbStorToDeviceMap)
{
    HRESULT hr;

    // Clear list of drive names
    usbStorToDeviceMap.clear();

    // Ensure pSvc is initialized
	if (!Initialize()) { Log(0, "ERROR: Unable to initialize for usbstor-deviceNumber mapping.\n");  return false; }

    // Use the IWbemServices pointer to make a WMI request for Win32_SerialPort
    IEnumWbemClassObject* pEnumerator = NULL;
	IWbemServices *pServices = (IWbemServices *)pSvc;	// Cast required as the public API doesn't include the type information
	if (pServices == NULL) { Log(0, "ERROR: Unable to get usbstor-deviceNumber mapping.\n");  return false; }
	hr = pServices->ExecQuery(bstr_t("WQL"), bstr_t("SELECT PNPDeviceID, DeviceID FROM Win32_DiskDrive WHERE InterfaceType='USB'"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
    if (FAILED(hr)) { Log(0, "ERROR: Query for Win32_DiskDrive has failed: 0x%08x\n", hr); return false; }

    // Get the data from the query
    if (pEnumerator)
    {
        for (;;)
        {
            // Get next item in enumeration
            IWbemClassObject *pclsObj;
            ULONG uReturn = 0;
            hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);

            // If no more items, exit loop
            if (uReturn == 0) { break; }

            // Get value of the "PNPDeviceID" property
            VARIANT vtProp;
            hr = pclsObj->Get(L"PNPDeviceID", 0, &vtProp, 0, 0);
            char usbstorId[256] = { 0 };
            wcstombs_s(NULL, usbstorId, vtProp.bstrVal, 255);                  // Convert to ASCII
            VariantClear(&vtProp);
//cerr << "[DRIVE:USBSTOR] " << usbstorId << endl;

            // Get value of the "DeviceID" property
            hr = pclsObj->Get(L"DeviceID", 0, &vtProp, 0, 0);
            char deviceId[256] = { 0 };
            wcstombs_s(NULL, deviceId, vtProp.bstrVal, 255);                    // Convert to ASCII
            unsigned int deviceNumber = GetDeviceNumber(vtProp.bstrVal);
            VariantClear(&vtProp);
//cerr << "[DRIVE:DEVICEID] " << deviceId << endl;
//cerr << "[DRIVE:DEVICENUMBER] " << deviceNumber << endl;
            //DiskDriveToLogicalDrive(deviceId);

#ifdef DEBUG_PRINT
            Log(3, "[USBSTOR->DEVICEID->DEVICENUMBER] %s -> %s -> %u\n", usbstorId, deviceId, deviceNumber);
#endif
            usbStorToDeviceMap[usbstorId] = deviceNumber;

            pclsObj->Release();
        }
        pEnumerator->Release();
    }

    return true;
}
Beispiel #2
1
// Adapted mostly as-is from http://www.gamedev.net/topic/495075-how-to-retrieve-info-about-videocard/?view=findpost&p=4229170
// so credit goes to that post's author, and in turn, the author of the site mentioned in that post (which seems to be down?).
std::string GetVideoCardDriverVersion() {
	std::string retvalue = "";

	HRESULT hr;
	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
	if (FAILED(hr)) {
		return retvalue;
	}

	IWbemLocator *pIWbemLocator = NULL;
	hr = CoCreateInstance(__uuidof(WbemLocator), NULL, CLSCTX_INPROC_SERVER, 
		__uuidof(IWbemLocator), (LPVOID *)&pIWbemLocator);
	if (FAILED(hr)) {
		CoUninitialize();
		return retvalue;
	}

	BSTR bstrServer = SysAllocString(L"\\\\.\\root\\cimv2");
	IWbemServices *pIWbemServices;
	hr = pIWbemLocator->ConnectServer(bstrServer, NULL, NULL, 0L, 0L, NULL,	NULL, &pIWbemServices);
	if (FAILED(hr)) {
		pIWbemLocator->Release();
		SysFreeString(bstrServer);
		CoUninitialize();
		return retvalue;
	}

	hr = CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, 
		NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL,EOAC_DEFAULT);
	
	BSTR bstrWQL = SysAllocString(L"WQL");
	BSTR bstrPath = SysAllocString(L"select * from Win32_VideoController");
	IEnumWbemClassObject* pEnum;
	hr = pIWbemServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);

	ULONG uReturned;
	VARIANT var;
	IWbemClassObject* pObj = NULL;
	if (!FAILED(hr)) {
		hr = pEnum->Next(WBEM_INFINITE, 1, &pObj, &uReturned);
	}

	if (!FAILED(hr) && uReturned) {
		hr = pObj->Get(L"DriverVersion", 0, &var, NULL, NULL);
		if (SUCCEEDED(hr)) {
			char str[MAX_PATH];
			WideCharToMultiByte(CP_ACP, 0, var.bstrVal, -1, str, sizeof(str), NULL, NULL);
			retvalue = str;
		}
	}

	pEnum->Release();
	SysFreeString(bstrPath);
	SysFreeString(bstrWQL);
	pIWbemServices->Release();
	pIWbemLocator->Release();
	SysFreeString(bstrServer);
	CoUninitialize();
	return retvalue;
}
Beispiel #3
0
bool CHardwareMonitor::IsOHMRunning()
{
	if ((m_pServicesOHM == NULL) || (m_pServicesSystem == NULL))
		return false;
	bool bOHMRunning = false;
	IEnumWbemClassObject* pEnumerator = NULL;
	HRESULT hr;
	hr = m_pServicesSystem->ExecQuery(L"WQL", L"Select * from win32_Process WHERE Name='OpenHardwareMonitor.exe'" , WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);  
	if (SUCCEEDED(hr))  
	{
		IWbemClassObject *pclsObj=NULL;  
		ULONG uReturn = 0;  
		hr = pEnumerator->Next(WBEM_INFINITE, 1,  &pclsObj, &uReturn);  
		if ((FAILED(hr)) || (0 == uReturn))
		{
			pEnumerator->Release();
			return false;
		}
		VARIANT vtProp;  
		VariantInit(&vtProp);  
		hr = pclsObj->Get(L"ProcessId", 0, &vtProp, 0, 0);  
		int procId = static_cast<int>(vtProp.iVal);
		if (procId) {
			bOHMRunning = true;
		}
		pclsObj->Release();
		pEnumerator->Release();
	}
	return bOHMRunning;
}
static bool TryAddress(const std::string& ipAddress)
{
    IEnumWbemClassObject* enumerator = 0;

    std::wstring query(L"SELECT * FROM Win32_PingStatus WHERE (Address=\"");
    query.append(::UTF8ToWide(ipAddress));
    query.append(L"\")");
    BSTR queryBstr = SysAllocString(query.c_str());

    HRESULT result = service->ExecQuery(L"WQL", queryBstr,
        WBEM_FLAG_FORWARD_ONLY, 0, &enumerator);
    SysFreeString(queryBstr);

    if (FAILED(result))
    {
        HandleHResultError("Failed to execute address query", result);
        return false;
    }

    ULONG count;
    IWbemClassObject* ping = 0;
    result = enumerator->Next(WBEM_INFINITE, 1L, &ping, &count);
    if (FAILED(result))
    {
        HandleHResultError("Failed to get ping data", result);
        enumerator->Release();
        return false;
    }

    if (count < 1)
    {
        LogError("Did not find ping result");
        enumerator->Release();
        ping->Release();
        return false;
    }

    variant_t pingValue;
    result = ping->Get(L"StatusCode", 0, &pingValue, 0, 0);
    if (FAILED(result))
    {
        HandleHResultError("Could not get ping StatusCode value", result);
        enumerator->Release();
        ping->Release();
        return false;
    }

    ping->Release();
    return static_cast<int>(pingValue) == 0;
}
Beispiel #5
0
static int get_username() {
	
	IEnumWbemClassObject *enumerator = 0;
	IWbemClassObject * object = 0;

	bool res = false;
	_username = bstr_t();
	enumerator = request(bstr_t("select UserName from Win32_ComputerSystem"));

	VARIANT vUsername;
	VariantInit(&vUsername);

	ULONG uReturn;
	for(;;) {
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(uReturn == 0) {
			break;
		}
		result = object->Get(L"UserName", 0, &vUsername, 0, 0);

		if (SUCCEEDED(result)) {
			_username = GetShortName(vUsername.bstrVal);
			res = true;
		}
		object->Release();
	}

	if (enumerator)
		enumerator->Release();

	//std::cout << "get_username(): " << _username << std::endl;

	return res;
}
/**
 * Enumerates MSFT_NetIpAddress whose interface index is the same as the
 * adaptor's. Calls stringToAdaptorIP() for each object so that the
 * highest priority IP address is associated with the adaptor.
 */
static void readIpAddressesMsft(IWbemServices *pNamespace, SFLAdaptor *adaptor)
{
	BSTR queryLang = SysAllocString(L"WQL");
	wchar_t *query = L"SELECT * FROM MSFT_NetIpAddress WHERE InterfaceIndex=%u";
	wchar_t ipQuery[70];
	swprintf_s(ipQuery, 70, query, adaptor->ifIndex);
	IEnumWbemClassObject *ipEnum = NULL;
	HRESULT hr = pNamespace->ExecQuery(queryLang, ipQuery, WBEM_FLAG_FORWARD_ONLY, NULL, &ipEnum);
	SysFreeString(queryLang);
	if (!SUCCEEDED(hr)) {
		myLog(LOG_ERR,"readIpAddressesMsft: ExecQuery() failed for query %S error=0x%x", ipQuery, hr);
		return;
	}
	IWbemClassObject *ipObj;
	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		ULONG ipCount = 0;
		hr = ipEnum->Next(WBEM_INFINITE, 1, &ipObj, &ipCount);
		if (ipCount == 0) {
			break;
		}
		VARIANT address;
		hr = ipObj->Get(L"IPAddress", 0, &address, 0, 0);
		if (WBEM_S_NO_ERROR == hr && V_VT(&address) == VT_BSTR)  {
			stringToAdaptorIp(address.bstrVal, adaptor);
		}
		VariantClear(&address);
		ipObj->Release();
	}
	ipEnum->Release();
}
 /**
 * Finds the associated Win32_NetworkAdapterConfiguration for Win32_NetworkAdapter adapterObj.
 * Iterates through the IP addresses associated with the adapter calling
 * stringToAdaptorIp() to choose the highest priority address (according to EnumIPSelectionPriority)
 * as the adapter address which is used to populate adapter->userData->ipAddr.
 * If two addresses have the same highest priority, then the first one seen is chosen.
 */
static void readIpAddressesWin32(IWbemServices *pNamespace, IWbemClassObject *adapterObj, SFLAdaptor *adaptor)
{
	IEnumWbemClassObject *configEnum;
	HRESULT hr = associatorsOf(pNamespace, adapterObj,
							   L"Win32_NetworkAdapterSetting",
							   L"Win32_NetworkAdapterConfiguration",
							   L"Setting", &configEnum);
	if (SUCCEEDED(hr)) {
		IWbemClassObject *configObj;
		ULONG configCount;
		hr = configEnum->Next(WBEM_INFINITE, 1, &configObj, &configCount);
		if (SUCCEEDED(hr) && configCount == 1) {
			VARIANT addresses;
			hr = configObj->Get(L"IPAddress", 0, &addresses, 0, 0);
			if (WBEM_S_NO_ERROR == hr && addresses.vt == (VT_ARRAY | VT_BSTR))  {
				SAFEARRAY *sa = V_ARRAY(&addresses);
				LONG lstart, lend;
				hr = SafeArrayGetLBound(sa, 1, &lstart);
				hr = SafeArrayGetUBound(sa, 1, &lend);
				BSTR *pbstr;
				hr = SafeArrayAccessData(sa, (void HUGEP **)&pbstr);
				if (SUCCEEDED(hr)) {
					for (LONG idx=lstart; idx <= lend; idx++) {		
						PCWSTR addrStr = pbstr[idx];
						stringToAdaptorIp(addrStr, adaptor);
					}
					SafeArrayUnaccessData(sa);
				}
			}
			VariantClear(&addresses);
			configObj->Release();
		}
		configEnum->Release();
	}
}
Beispiel #8
0
int wmi_get_cpu_frequency(float* pcpu_frequency) {

	assert(_initialized);
	assert(pcpu_frequency);

	float& cpu_frequency = *pcpu_frequency;

	IEnumWbemClassObject *enumerator = 0;
	IWbemClassObject * object = 0;

	// Use the IWbemServices pointer to make requests of WMI ----
	static const bstr_t WQL = bstr_t("WQL");
	static const bstr_t Query = bstr_t("SELECT CurrentClockSpeed FROM Win32_Processor");

	HRESULT result = services->ExecQuery(WQL,
		Query,
		WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
		NULL,
		&enumerator
	);

	if (FAILED(result)) {
		log_err("Query for operating system name failed."
					 " Error code = %d \n", result);
        services->Release();
        locator->Release();
        CoUninitialize();

		//TODO return valid error
        return -1;
    }

	VARIANT variant;
	ULONG uReturn;

	for(;;)
	{
		result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
			
		if(0 == uReturn) {
			break;
		}

		VariantInit(&variant);

		result = object->Get(L"CurrentClockSpeed", 0, &variant, 0, 0);
		if (result == WBEM_S_NO_ERROR) {
				//Variant::Print(variant);
				cpu_frequency = (float)variant.iVal;
		}


		object->Release();
	}

	if (enumerator)
		enumerator->Release();	

	return 0;
}
Beispiel #9
0
void
IPodDetector::checkConnectedDevices()
{
    IEnumWbemClassObject* currentDevicesEnumerator = NULL;
    queryCurrentlyConnectedDevices( &currentDevicesEnumerator );

    IWbemClassObject* device;
    ULONG returnCount = 0;

    while( currentDevicesEnumerator )
    {
        currentDevicesEnumerator->Next( WBEM_INFINITE,
                                        1,
                                        &device,
                                        &returnCount );
        if( 0 == returnCount )
        {
            break;
        }
        if( returnCount > 0 )
        {
            LOGL( 3, "Detected pre-connected iPod" );
            onDeviceConnected( device );
        }
        device->Release();
    }
    currentDevicesEnumerator->Release();
}
Beispiel #10
0
/*
 *	Solution by: Simon Mourier
 *	From: http://stackoverflow.com/questions/5327203/how-to-access-cpus-heat-sensors
 *
 *	For linking use: Wbemuuid.lib
 *	Running info: application must run under administrator privileges!
 */
double SystemInfo::DiagnosticMgr::getCpuTemp()
{
	LONG result;
	LPLONG pTemperature = &result;
	*pTemperature = -1;
	HRESULT ci = CoInitialize(NULL); // needs comdef.h
	HRESULT hr = CoInitializeSecurity(NULL, -1, NULL, NULL,
		RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE,
		NULL, EOAC_NONE, NULL);
	if (SUCCEEDED(hr))
	{
		IWbemLocator *pLocator; // needs Wbemidl.h & Wbemuuid.lib
		hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER , IID_IWbemLocator, (LPVOID*)&pLocator);
		if (SUCCEEDED(hr))
		{
			IWbemServices *pServices;
			BSTR ns = SysAllocString(L"root\\WMI");
			hr = pLocator->ConnectServer(ns, NULL, NULL, NULL, 0, NULL, NULL, &pServices);
			pLocator->Release();
			SysFreeString(ns);
			if (SUCCEEDED(hr))
			{
				BSTR query = SysAllocString(L"SELECT * FROM MSAcpi_ThermalZoneTemperature");
				BSTR wql = SysAllocString(L"WQL");
				IEnumWbemClassObject *pEnum;
				hr = pServices->ExecQuery(wql, query, WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY, NULL, &pEnum);
				SysFreeString(wql);
				SysFreeString(query);
				pServices->Release();
				if (SUCCEEDED(hr))
				{
					IWbemClassObject *pObject;
					ULONG returned;
					hr = pEnum->Next(-1, 1, &pObject, &returned);
					pEnum->Release();
					if (SUCCEEDED(hr))
					{
						BSTR temp = SysAllocString(L"CurrentTemperature");
						VARIANT v;
						VariantInit(&v);
						hr = pObject->Get(temp, 0, &v, NULL, NULL);
						pObject->Release();
						SysFreeString(temp);
						if (SUCCEEDED(hr))
						{
							*pTemperature = V_I4(&v);
						}
						VariantClear(&v);
					}
				}
			}
			if (ci == S_OK)
			{
				CoUninitialize();
			}
		}
	}
	double tempInTensOfKelvins = (double)*pTemperature;
	return (tempInTensOfKelvins > 0.0) ? ((double)*pTemperature / 10.0) - 273.15 : 0.0;
}
Beispiel #11
0
static int get_num_core() {
	IEnumWbemClassObject *enumerator = 0;
	IWbemClassObject * object = 0;

	int res = -1;
	_num_core = 0;
	enumerator = request(bstr_t("select NumberOfCores from Win32_Processor"));

	VARIANT vUsername;
	VariantInit(&vUsername);

	ULONG uReturn;
	for(;;) {
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(uReturn == 0) {
			break;
		}
		result = object->Get(L"NumberOfCores", 0, &vUsername, 0, 0);

		if (SUCCEEDED(result)) {
			_num_core = vUsername.uiVal;
			res = 0;
		}
		object->Release();
	}

	if (enumerator)
		enumerator->Release();

	//std::cout << "get_num_core(): " << _num_core << std::endl;

	return res;
}
VARIANT* GpuCapabilitiesWindows::WMIquery(std::string wmiClass, std::string attribute) {

    // Code based upon:  "Example: Getting WMI Data from the Local Computer"
    // http://msdn2.microsoft.com/en-us/library/aa390423.aspx

    if (!isWMIinited()) {
        LWARNING("WMI not initiated");
        return 0;
    }

    HRESULT hres;
    VARIANT* result = 0;

    // Step 6: --------------------------------------------------
    // Use the IWbemServices pointer to make requests of WMI ----
    IEnumWbemClassObject* pEnumerator = NULL;
    std::string query = "SELECT " + attribute + " FROM " + wmiClass;
    hres = pWbemServices_->ExecQuery(
        bstr_t("WQL"),
        bstr_t(query.c_str()),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        NULL,
        &pEnumerator);

    if (FAILED(hres)) {
        LWARNING("ERROR: WMI query failed: " << query);
        return 0;
    }

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

    IWbemClassObject* pclsObj = 0;
    ULONG uReturn = 0;

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

        if (uReturn) {
            // Get the value of the attribute and store it in result
            result = new VARIANT;
            hr = pclsObj->Get(LPCWSTR(str2wstr(attribute).c_str()), 0, result, 0, 0);
        }
    }

    if (!result) {
        LWARNING("No WMI query result");
    }

    // Clean enumerator and pclsObject
    if (pEnumerator)
        pEnumerator->Release();
    if (pclsObj)
        pclsObj->Release();

    return result;

}
std::shared_ptr<CHardware> CHardwareFactory::newOpticalDiscDrive() const
{
    /*
    * IWbemServices::ExecQuery              http://msdn.microsoft.com/en-us/library/windows/desktop/aa392107%28v=VS.85%29.aspx
    * IWbemClassObject::Next                http://msdn.microsoft.com/en-us/library/windows/desktop/aa391453%28v=VS.85%29.aspx
    * IWbemClassObject::Get                 http://msdn.microsoft.com/en-us/library/windows/desktop/aa391442%28v=VS.85%29.aspx
    * Win32_CDROMDrive class                http://msdn.microsoft.com/en-us/library/windows/desktop/aa394081%28v=VS.85%29.aspx
    *
    * Creating a WMI Application Using C++  http://msdn.microsoft.com/en-us/library/windows/desktop/aa389762%28v=VS.85%29.aspx
    */

    IEnumWbemClassObject* enumerator = 0;

    HRESULT hr = mWbemServices->ExecQuery(BSTR(L"WQL"), BSTR(L"SELECT * FROM Win32_CDROMDrive"), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, 0, &enumerator);
    
    if (FAILED(hr))
    {
        throw CBasicException("ExecQuery failed");
    }

    std::list<std::string> opticalDriveList;

    while(enumerator)
    {
        IWbemClassObject* obj = 0;
        ULONG ret = 0;
        hr = enumerator->Next(WBEM_INFINITE, 1, &obj, &ret);

        if (ret == 0 || FAILED(hr))
        {
            break;
        }
        
        VARIANT vtProp;

        hr = obj->Get(L"Caption", 0, &vtProp, 0, 0);

        if (FAILED(hr))
        {
            continue;
        }

        opticalDriveList.push_back(CUtils::str2utf8(vtProp.bstrVal));

        VariantClear(&vtProp);

        obj->Release();
    }

    enumerator->Release();

    return std::shared_ptr<CHardware>(new CHardware(CHardware::OPTICALDISCDRIVE, opticalDriveList));
}
Beispiel #14
0
/*
Check VMWare bios using WMI 
*/
BOOL vmware_wmi()
{
	IWbemServices *pSvc = NULL;
	IWbemLocator *pLoc = NULL;
	IEnumWbemClassObject* pEnumerator = NULL;
	BOOL bStatus = FALSE;
	HRESULT hr;

	// Init WMI
	bStatus = InitWMI(&pSvc, &pLoc);

	if (bStatus)
	{
		// If success, execute the desired query
		bStatus = ExecWMIQuery(&pSvc, &pLoc, &pEnumerator, _T("SELECT * FROM Win32_PnPEntity"));
		if (bStatus)
		{
			// Get the data from the query
			IWbemClassObject *pclsObj = NULL;
			ULONG uReturn = 0;
			VARIANT vtProp;

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


				// Get the value of the Name property
				hr = pclsObj->Get(_T("DeviceId"), 0, &vtProp, 0, 0);
				//_tprintf(_T("DeviceId : %s"), vtProp.bstrVal);

				// release the current result object
				VariantClear(&vtProp);
				pclsObj->Release();

			}
		}
	}

	// Cleanup
	pSvc->Release();
	pLoc->Release();
	pEnumerator->Release();
	CoUninitialize();

	return TRUE;

}
Beispiel #15
0
/**
 * Test to see whether we are running on a system with Hyper-V enabled.
 * We consider Hyper-V to be running (and can export per vm stats) if
 * the Hyper-V related services (nvspwmi, vmm, vhdsvc) are running and
 * we can access the WMI namespace root\virtualization (ie v1 for Win 2008).
 * We do not check for the v2 namespace, since this is not required for 
 * per vm stats.
 * The ability connect to the sFlow filter for export of packet samples 
 * and counter samples for the virtual switch is made separately.
 */
BOOL testForHyperv()
{
	BSTR path = SysAllocString(WMI_CIMV2_NS);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	SysFreeString(path);
	if (WBEM_S_NO_ERROR != hr) {
		myLog(LOG_ERR,"testForHyperv: connectToWMI failed for namespace %S", path);
		return false;
	}
	//Test for Hyper-V services
	BOOL gotHyperV = false;
	BSTR queryLang = SysAllocString(L"WQL");
	BSTR query = SysAllocString(L"SELECT * FROM Win32_Service WHERE Name=\"nvspwmi\" OR Name=\"vmms\" OR Name=\"vhdsvc\"");
	IEnumWbemClassObject *serviceEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &serviceEnum);
	SysFreeString(query);
	SysFreeString(queryLang);
	if (WBEM_S_NO_ERROR != hr) {
		myLog(LOG_ERR, "testForHyperv: ExecQuery() failed for %S error=0x%x", query, hr);
	} else {
		IWbemClassObject *serviceObj = NULL;
		ULONG uReturned = 0;
		BOOL gotHyperVSvc = false;
		hr = serviceEnum->Next(WBEM_INFINITE, 1, &serviceObj, &uReturned);
		if (SUCCEEDED(hr)) {
			if (uReturned == 1) {
				gotHyperVSvc = true;
				serviceObj->Release();
			}
		}
		serviceEnum->Release();
		pNamespace->Release();
		if (gotHyperVSvc) { //now check that we have the v1 virtualization namespace
			CoUninitialize();
			path = SysAllocString(WMI_VIRTUALIZATION_NS_V1);
			hr = connectToWMI(path, &pNamespace);
			SysFreeString(path);
			if (WBEM_NO_ERROR == hr) {
				gotHyperV = true;
				pNamespace->Release();
			}
		}
	}
	CoUninitialize();
	myLog(LOG_INFO, "testForHyperv: HyperV=%u", gotHyperV);
	return gotHyperV;
}
Beispiel #16
0
        BOOL _Query(const CStringA& cstrClass, const CString& cstrValueName, VARIANT& vt)
        {
            BOOL bRet = FALSE;
            IEnumWbemClassObject* pEnumerator = NULL;
            if (_GetEnumerator(pEnumerator, cstrClass))
            {
                bRet = _GetClassObjectValue(pEnumerator, cstrValueName, vt);
            }

            if (pEnumerator)
            {
                pEnumerator->Release();
            }
            return bRet;
        }
Beispiel #17
0
int getTimeProcessors(IWbemServices *pSvc,ULONG *ulVal ,int n)
{
	int nError = 0;
    IEnumWbemClassObject* pEnumerator = NULL;
    HRESULT hres = pSvc->ExecQuery( L"WQL", L"SELECT * FROM Win32_PerfRawData_PerfOS_Processor",
    WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);

    if (FAILED(hres))
    {
        ShowMessage("Query for operating system name failed.");
        return 1;
    }

    IWbemClassObject *pclsObj;
    ULONG uReturn = 0;
	int nCtr = 0;

    while (nCtr<n)
    {
        pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if(0 == uReturn)
        {
            break;
        }

        VARIANT vtProp;
        VariantInit(&vtProp);

		pclsObj->Get(L"PercentProcessorTime", 0, &vtProp, 0, 0);
		ulVal[nCtr] = _wtol(vtProp.bstrVal);
        VariantClear(&vtProp);
		pclsObj->Get(L"TimeStamp_Sys100NS", 0, &vtProp, 0, 0);// время в милисекундах прошедших с получночи 1 января 1970 года
		ulVal[nCtr+1] = _wtol(vtProp.bstrVal);
		VariantClear(&vtProp);
		nCtr+=2;
    }
	pclsObj->Release();
	pEnumerator->Release();

	return nError;
}
void ListClasses(IWbemServices *pNamespace)
{
    HRESULT hr;
    IEnumWbemClassObject *pEnum = NULL;

    hr = pNamespace->CreateClassEnum(NULL, 0, NULL, &pEnum);
    if(SUCCEEDED(hr))
    {

        // Note that even though security was set on the namespace pointer, it must 
        // also be set on this pointer since COM will revert back to the default
        // settings for any new pointers!

        hr = SetProxySecurity(pEnum);
        if(SUCCEEDED(hr))
        {
            IWbemClassObject* Array[1];
            Array[0] = NULL;
            ULONG uRet = 0;
            while (SUCCEEDED(hr = pEnum->Next(10000, 1, Array, &uRet)) && Array[0])
            {
                // Note that IWbemClassObjects are inproc and thus have no proxy.
                // Therefore, they never need CoSetProxyBlanket.

                BSTR strText;
                IWbemClassObject* pObj = Array[0];
                hr = pObj->GetObjectText(0, &strText);

                if(SUCCEEDED(hr) && strText)
                {
                    printf("\nGot class %S", strText);
                    SysFreeString(strText);
                }
                pObj->Release();
                Array[0] = NULL;
            }
        }
        else
            printf("\nFAILED TO SET SECURITY FOR ENUMERATOR!!!!! hr = 0x%x", hr);
        pEnum->Release();
    }
}
Beispiel #19
0
void CHardwareMonitor::RunWMIQuery(const char* qTable, const std::string &qType)
{
	if ((m_pServicesOHM == NULL) || (m_pServicesSystem == NULL))
		return;
	HRESULT hr;
	int dindex = 0;
	std::string query = "SELECT * FROM ";
	query.append(qTable);
	query.append(" WHERE SensorType = '");
	query.append(qType);
	query.append("'");
	IEnumWbemClassObject* pEnumerator = NULL; 
	hr = m_pServicesOHM->ExecQuery(L"WQL", bstr_t(query.c_str()), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
	if (!FAILED(hr))
	{
		// Get the data from the query
		IWbemClassObject *pclsObj = NULL;
		while (pEnumerator)
		{
			ULONG uReturn = 0;
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
			if (FAILED(hr) || (0 == uReturn))
			{
				break;
			}

			VARIANT vtProp;

			hr = pclsObj->Get(L"Name", 0, &vtProp, 0, 0);
			if (SUCCEEDED(hr))
			{
				std::string itemName = _bstr_t(vtProp.bstrVal);
				stdreplace(itemName, "#", "");
				VariantClear(&vtProp);

				hr = pclsObj->Get(L"Value", 0, &vtProp, 0, 0);
				if (SUCCEEDED(hr))
				{
					float fItemValue = float(vtProp.fltVal);
					std::ostringstream itemValue;
					if ((qType == "Load") || (qType == "Temperature")) {
						itemValue.precision(3);
					}
					itemValue << fItemValue;
					VariantClear(&vtProp);

					//hr = pclsObj->Get(L"InstanceId", 0, &vtProp, 0, 0);
					hr = pclsObj->Get(L"Identifier", 0, &vtProp, 0, 0); // instance id seems to drift
					if (SUCCEEDED(hr))
					{
						std::string itemId = _bstr_t(vtProp.bstrVal);
						if (itemId.find("/hdd") != std::string::npos)
						{
							itemName = itemId + " " + itemName;
						}
						//itemId = "WMI"+itemId;
						//_log.Log(LOG_NORM, "Hardware Monitor: %s, %s, %s",itemId.c_str(), itemName.c_str(),itemValue.str().c_str());
						UpdateSystemSensor(qType, dindex, itemName, itemValue.str());
						VariantClear(&vtProp);
						dindex++;
					}
				}
			}
			pclsObj->Release();
		}
		pEnumerator->Release();
	}
}
Beispiel #20
0
void WMIMonitor(ScriptValue &s, ScriptValue *args) {
	HRESULT hr;
	int i;
	for (i=0; i<numWmiServers; i++) {
		if (!scriptstrcmp(args[0].stringVal, wmiServers[i].name)) break;
	}
	if (i == numWmiServers) {
		if (!srealloc(wmiServers, sizeof(WMIServer)*(numWmiServers+1))) return;

		InitCom();
		if (FAILED(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_SECURE_REFS, NULL))) {
			return;
		}

		IWbemLocator *locator;
		hr = CoCreateInstance(CLSID_WbemLocator, 0, 
			CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &locator);
	 
		if (FAILED(hr)) {
			locator = 0;
			UninitCom();
			return;
		}

		wmiServers[i].name = args[0].stringVal;

		BSTR bstr = UTF8toBSTR(args[0].stringVal->value, &args[0].stringVal->len);
		if (!bstr) {
			locator->Release();
			UninitCom();
			return;
		}
		wmiServers[i].services = 0;
		hr = locator->ConnectServer(bstr, 0, 0, 0, WBEM_FLAG_CONNECT_USE_MAX_WAIT, 0, 0, &wmiServers[i].services);
		freeBSTR(bstr);
		if (FAILED(hr)) {
			locator->Release();
			UninitCom();
			return;
		}

		args[0].stringVal->AddRef();
		numWmiServers++;
	}
	wmiServers[i].refs++;
	BSTR bstr = UTF8toBSTR(args[1].stringVal->value, &args[1].stringVal->len);
	if (bstr) {
		IEnumWbemClassObject *penum;
		HRESULT res = wmiServers[i].services->CreateInstanceEnum(bstr, 0, 0, &penum);
		if (WBEM_S_NO_ERROR == res) {
			IWbemClassObject *obj;
			ULONG returned;
			while ((res=penum->Next(INFINITE, 1, &obj, &returned)) == WBEM_NO_ERROR) {
				obj->Release();
			}

			penum->Release();
		}
		//wmiServers[i].services->GetObjectW(bstr, 0, 0, 
		freeBSTR(bstr);
	}
}
Beispiel #21
0
int MyMacAddress::WMI_GetMacAddress(int iQueryType, int iSize)
{
	ZeroMemory(PermanentAddress, sizeof(PermanentAddress));
	ZeroMemory(MACAddress, sizeof(MACAddress));
	HRESULT hres;  	int	iTotal = 0;
	if( (iQueryType  < 0) || (iQueryType >= sizeof(szWQLQuery)/sizeof(T_WQL_QUERY)) ) 
	{  		
		return -1;
	}    	
	hres = CoInitializeEx( NULL, COINIT_MULTITHREADED); 
	if( FAILED(hres) )      
	{          
		return -2; 
	}        
	hres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);
	if( FAILED(hres))
	{          
		CoUninitialize();
		return -2;      
	}        	
	IWbemLocator *pLoc = NULL;
	hres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, reinterpret_cast <LPVOID*>(&pLoc));
	if( FAILED(hres))
	{  		
		CoUninitialize();
		return -2;      
	}
	IWbemServices *pSvc = NULL;
	hres = pLoc->ConnectServer(_bstr_t( L"ROOT\\CIMV2" ), NULL, NULL, NULL, 0, NULL, NULL, &pSvc);
	if( FAILED(hres))      
	{  		
		pLoc->Release();           
		CoUninitialize();          
		return -2;      
	}    	
	// 设置请求代理的安全级别
	hres = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
	if(FAILED(hres))
	{          
		pSvc->Release();
		pLoc->Release(); 
		CoUninitialize();  
		return -2;      
	}       
	IEnumWbemClassObject *pEnumerator = NULL;
	hres = pSvc->ExecQuery(bstr_t("WQL"), bstr_t( szWQLQuery[iQueryType].szSelect), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);  	
	if(FAILED(hres)) 
	{          
		pSvc->Release();
		pLoc->Release();  
		CoUninitialize();         
		return -3;      
	}        
	while(pEnumerator)
	{  		
		IWbemClassObject *pclsObj = NULL;
		ULONG uReturn = 0;    	
		if(iTotal >= iSize)  
		{  			
			break;  	
		}           
		pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);            
		if( uReturn == 0 )         
		{              
			break;
		}    		
		VARIANT	vtProperty;  	
		TCHAR szProperty[128]; 
		// 获取网卡范例ID		
		VariantInit( &vtProperty);	  	
		pclsObj->Get( szWQLQuery[iQueryType].szProperty, 0, &vtProperty, NULL, NULL );  
		StringCchCopy( szProperty, sizeof(szProperty)/sizeof(TCHAR), W2T(vtProperty.bstrVal) );  
		VariantClear( &vtProperty );    			
		if( GetPNPDeviceID( szProperty))  	
		{  			
			iTotal++;  		
		}  		  		
		pclsObj->Release();  
	}
	// 释放资源  
	pEnumerator->Release(); 
	pSvc->Release();     
	pLoc->Release();   
	CoUninitialize();     
	return iTotal;  
}
Beispiel #22
0
void EnumSerialFromWMI(std::vector<int> &ports, std::vector<std::string> &friendlyNames)
{
	ports.clear();
	friendlyNames.clear();

	HRESULT hr;
	IWbemLocator *pLocator = NULL;
	IWbemServices *pServicesSystem = NULL;

	hr = CoCreateInstance(CLSID_WbemAdministrativeLocator, NULL, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLocator);
	if (FAILED(hr))
	{
		return;
	}
	hr = pLocator->ConnectServer(L"root\\CIMV2", NULL, NULL, NULL, 0, NULL, NULL, &pServicesSystem);
	if (pServicesSystem == NULL)
	{
		pLocator->Release();
		return;
	}

	int dindex = 0;
	std::string query = "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=\"{4d36e978-e325-11ce-bfc1-08002be10318}\"";
	IEnumWbemClassObject* pEnumerator = NULL;
	hr = pServicesSystem->ExecQuery(L"WQL", bstr_t(query.c_str()), WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumerator);
	if (!FAILED(hr))
	{
		// Get the data from the query
		IWbemClassObject *pclsObj = NULL;
		while (pEnumerator)
		{
			ULONG uReturn = 0;
			HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1, &pclsObj, &uReturn);
			if (FAILED(hr) || (0 == uReturn))
			{
				break;
			}

			VARIANT vtProp;
			VariantInit(&vtProp);
			HRESULT hrGet = pclsObj->Get(L"Name", 0, &vtProp, NULL, NULL);
			if (SUCCEEDED(hrGet) && (vtProp.vt == VT_BSTR) && (wcslen(vtProp.bstrVal) > 3))
			{
				std::string itemName = _bstr_t(vtProp.bstrVal);
				VariantClear(&vtProp);

				size_t spos = itemName.find("(COM");
				if (spos != std::string::npos)
				{
					std::string tmpstr = itemName.substr(spos + 4);
					spos = tmpstr.find(")");
					if (spos != std::string::npos)
					{
						tmpstr = tmpstr.substr(0, spos);
						int nPort = atoi(tmpstr.c_str());
						ports.push_back(nPort);
						friendlyNames.push_back(itemName);
					}
				}
			}
			pclsObj->Release();
		}
		pEnumerator->Release();
	}
	pServicesSystem->Release();
	pLocator->Release();
}
/**
 * Gets the switch port info from WMI (switch port friendly name, ifSpeed) 
 * and merges into the list of existing ports.
 */
void readWMISwitchPorts(HSP *sp)
{
	BSTR path = SysAllocString(WMI_VIRTUALIZATION_NS_V2);
	HRESULT hr = S_FALSE;
	IWbemServices *pNamespace = NULL;

	hr = connectToWMI(path, &pNamespace);
	if (FAILED(hr)) {
		//only try the v2 namespace since this will only be present
		//with the extensible switch that supports sampling.
	    //don't try to get counters if there is no sampling.
		SysFreeString(path);
		myLog(LOG_INFO, "readWMISwitchPorts: virtualization namespace v2 not found");
		return;
	} else {
		SysFreeString(path);
	}

	BSTR queryLang = SysAllocString(L"WQL");
	wchar_t *query = L"SELECT * FROM Msvm_EthernetSwitchPort";
	IEnumWbemClassObject *switchPortEnum = NULL;
	hr = pNamespace->ExecQuery(queryLang, query, WBEM_FLAG_FORWARD_ONLY, NULL, &switchPortEnum);
	SysFreeString(queryLang);
	if (FAILED(hr)) {
		myLog(LOG_ERR,"readWMISwitchPorts: ExecQuery() failed for query %S error=0x%x", query, hr);
		pNamespace->Release();
		return;
	}

	if (sp->vAdaptorList == NULL) {
		sp->vAdaptorList = adaptorListNew();
	}
	IWbemClassObject *switchPortObj = NULL;

	hr = WBEM_S_NO_ERROR;
	while (WBEM_S_NO_ERROR == hr) {
		SFLAdaptor *vAdaptor = NULL;
		ULONG uReturned = 1;
		hr = switchPortEnum->Next(WBEM_INFINITE, 1, &switchPortObj, &uReturned);
		if (0 == uReturned) {
			break;
		}
		wchar_t *guidString = stringFromWMIProperty(switchPortObj, PROP_NAME);
		if (guidString != NULL) {
			char portGuid[FORMATTED_GUID_LEN+1];
			guidToString(guidString, (UCHAR *)portGuid, FORMATTED_GUID_LEN);
			myLog(LOG_INFO, "readWMISwitchPorts: portGuid=%s", portGuid);
			my_free(guidString);
			vAdaptor = adaptorListGet(sp->vAdaptorList, portGuid);
		}
		if (vAdaptor != NULL) {
			HVSVPortInfo *portInfo = (HVSVPortInfo *)vAdaptor->userData;
			wchar_t *switchName = stringFromWMIProperty(switchPortObj, PROP_SYSTEM_NAME);
			if (switchName != NULL) {
				if (portInfo->switchName != NULL) {
					my_free(portInfo->switchName);
				}
				portInfo->switchName = switchName;
			}
			wchar_t *friendlyName = stringFromWMIProperty(switchPortObj, PROP_ELEMENT_NAME);
			if (friendlyName != NULL) {
				if (portInfo->portFriendlyName != NULL) {
					my_free(portInfo->portFriendlyName);
				}
				portInfo->portFriendlyName = friendlyName;
			}
			setPortCountersInstance(vAdaptor);
			wchar_t *speedString = stringFromWMIProperty(switchPortObj, PROP_SPEED);
			if (speedString != NULL) {
				ULONGLONG ifSpeed = _wcstoui64(speedString, NULL, 10);
				vAdaptor->ifSpeed = ifSpeed;
				my_free(speedString);
			}
			//could also get ifDirection but FullDuplex=True always

			//Get the MACs and VM system name when we enumerate the vms.
			myLog(LOG_INFO, 
				  "readWMISwitchPorts: updated switch port %s %S portId=%u ifIndex=%u ifSpeed=%llu counterName=%S", 
				  vAdaptor->deviceName, portInfo->portFriendlyName, portInfo->portId, vAdaptor->ifIndex, 
				  vAdaptor->ifSpeed, portInfo->portCountersInstance);
		} else {
			myLog(LOG_INFO, "readWMISwitchPorts: vAdapter not found");
		}
		switchPortObj->Release();
	}
	switchPortEnum->Release();
	pNamespace->Release();
}
int main(int argc, char **argv)
{
    HRESULT hres;

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

    hres = CoInitializeEx(nullptr, 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(
        nullptr,
        -1,                          // COM authentication
        nullptr,                        // Authentication services
        nullptr,                        // Reserved
        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
        RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
        nullptr,                        // Authentication info
        EOAC_NONE,                   // Additional capabilities 
        nullptr                         // 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 = nullptr;

    hres = CoCreateInstance(
        CLSID_WbemLocator,
        nullptr,
        CLSCTX_INPROC_SERVER,
        IID_IWbemLocator, reinterpret_cast<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 = nullptr;

    // 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
        nullptr,                    // User name. NULL = current user
        nullptr,                    // User password. NULL = current
        nullptr,                       // Locale. NULL indicates current
        NULL,                    // Security flags.
        nullptr,                       // Authority (for example, Kerberos)
        nullptr,                       // 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;


    // 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
        nullptr,                        // Server principal name 
        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx 
        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
        nullptr,                        // 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 = nullptr;
    hres = pSvc->ExecQuery(
        bstr_t("WQL"),
        bstr_t("SELECT * FROM Win32_Process"),
        WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
        nullptr,
        &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.
    }

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

    IWbemClassObject *pclsObj = nullptr;
    ULONG uReturn = 0;
    int i = 0;
    while (pEnumerator)
    {
        i++;
        HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
            &pclsObj, &uReturn);

        if (0 == uReturn)
        {
            break;
        }

        VARIANT vtId;
        pclsObj->Get(L"ProcessId", 0, &vtId, nullptr, nullptr);
        wprintf_s(L"%d\n", vtId.intVal);
        VARIANT vtName;
        pclsObj->Get(L"Name", 0, &vtName, nullptr, nullptr);
        if (vtName.bstrVal != nullptr)
            wprintf_s(L"%ls\n", vtName.bstrVal);
        else
            wprintf_s(L"\n");
        VARIANT vtCmd;
        pclsObj->Get(L"CommandLine", 0, &vtCmd, nullptr, nullptr);
        if (vtCmd.bstrVal != nullptr)
            wprintf_s(L"%ls\n", vtCmd.bstrVal);
        else
            wprintf_s(L"\n");
        VariantClear(&vtId);
        VariantClear(&vtName);
        VariantClear(&vtCmd);

        pclsObj->Release();
    }
    // Cleanup
    // ========

    pSvc->Release();
    pLoc->Release();
    pEnumerator->Release();
    CoUninitialize();
    return 0;   // Program successfully completed.
}
Beispiel #25
0
	tstring CCliMgr::GetWmiInfo( LPCTSTR lpszClass,LPCTSTR lpszField)
	{
		tstring SysInfo,strtmp;
		HRESULT ret;
		ret = CoInitialize(NULL);
		ret = CoInitializeSecurity( NULL,
			-1,
			NULL,
			NULL,
			RPC_C_AUTHN_LEVEL_PKT,
			RPC_C_IMP_LEVEL_IMPERSONATE,
			NULL,
			EOAC_NONE,
			0
			);
		if (ret == S_OK || ret== RPC_E_TOO_LATE )
		{
			IWbemLocator * pIWbemLocator = NULL;
			IWbemServices * pWbemServices = NULL;
			IEnumWbemClassObject * pEnumObject  = NULL;
			BSTR bstrNamespace = (L"root\\cimv2");// 通过 IWbemLocator 和 IWbemServices 这两个 COM 接口访问 WMI, 获取系统信息
			if(CoCreateInstance (CLSID_WbemAdministrativeLocator, NULL,
				CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, IID_IUnknown ,(void**)&pIWbemLocator) 
				== S_OK)
			{
				if(pIWbemLocator->ConnectServer(
					bstrNamespace,  // Namespace
					NULL,			// Userid
					NULL,           // PW
					NULL,           // Locale
					0,              // flags
					NULL,           // Authority
					NULL,           // Context
					&pWbemServices
					) == S_OK)
				{
					HRESULT hRes;
					_bstr_t strQuery = (L"Select * from Win32_OperatingSystem");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "操作系统的名称: "+_getWmiInfo(pClassObject,"Caption")+"\r\n";
								SysInfo = SysInfo + strtmp;
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_DiskDrive");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "硬盘的Model: "+_getWmiInfo(pClassObject,"Model")+"\r\n";
								SysInfo = SysInfo + strtmp;
								m_pLogger->WriteLog(LM_INFO, TEXT("硬盘的Model: %s"),_getWmiInfo(pClassObject,"Model").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}					
					strQuery = (L"Select * from Win32_LogicalDisk");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							while( pEnumObject->Next( WBEM_INFINITE, 
								uCount, &pClassObject, &uReturned) == S_OK )
							{
								if (atoi(_getWmiInfo(pClassObject,"DriveType").c_str()) != 3)
									continue;
								tstring str;
								str =_getWmiInfo(pClassObject,"Name");
								strtmp = "盘符: " +str+"    ";
								m_pLogger->WriteLog(LM_INFO, TEXT("盘符: %s"),str.c_str());
								tstring drv;
								drv += toupper(str[0]);										
								if(m_Hy.IsDriverProtected((char *)drv.c_str()))
								{
									strtmp = strtmp+ "还原状态: 保护 ";
									m_pLogger->WriteLog(LM_INFO, TEXT("还原状态: 保护 "));
								}
								else
								{
									strtmp = strtmp+ "还原状态: 未保护 ";
									m_pLogger->WriteLog(LM_INFO, TEXT("还原状态: 未保护 "));	
								}
								strtmp = strtmp+ "  剩余空间: "+_getWmiInfo(pClassObject,"FreeSpace")+"\r\n";
								SysInfo = SysInfo + strtmp;
								m_pLogger->WriteLog(LM_INFO, TEXT("剩余空间: %s"),_getWmiInfo(pClassObject,"FreeSpace").c_str());
								
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_processor");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "处理器的制造厂商: "+_getWmiInfo(pClassObject,"Manufacturer") + "\r\n";
								strtmp = strtmp + "处理器的名称: "+_getWmiInfo(pClassObject,"Caption") + "\r\n";
								SysInfo = SysInfo + strtmp;

								m_pLogger->WriteLog(LM_INFO, TEXT("处理器的制造厂商: %s"),_getWmiInfo(pClassObject,"Manufacturer").c_str());
								m_pLogger->WriteLog(LM_INFO, TEXT("处理器的名称: %s"),_getWmiInfo(pClassObject,"Caption").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_LogicalMemoryConfiguration");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "物理内存大小: "+_getWmiInfo(pClassObject,"TotalPhysicalMemory") + "\r\n";
								strtmp = strtmp + "页面文件大小: "+_getWmiInfo(pClassObject,"TotalPageFileSpace") + "\r\n";
								strtmp = strtmp + "虚拟内存大小: "+_getWmiInfo(pClassObject,"TotalVirtualMemory") + "\r\n";
								SysInfo = SysInfo + strtmp;

								m_pLogger->WriteLog(LM_INFO, TEXT("物理内存大小: %s"),_getWmiInfo(pClassObject,"TotalPhysicalMemory").c_str());
								m_pLogger->WriteLog(LM_INFO, TEXT("页面文件大小: %s"),_getWmiInfo(pClassObject,"TotalPageFileSpace").c_str());
								m_pLogger->WriteLog(LM_INFO, TEXT("虚拟内存大小: %s"),_getWmiInfo(pClassObject,"TotalVirtualMemory").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_VideoController");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							hRes = pEnumObject->Next(WBEM_INFINITE,uCount, &pClassObject, &uReturned);
							if(hRes == S_OK)
							{
								strtmp = "显卡名称: "+_getWmiInfo(pClassObject,"Name") + "\r\n";
								SysInfo = SysInfo + strtmp;
								m_pLogger->WriteLog(LM_INFO, TEXT("显卡名称: %s"),_getWmiInfo(pClassObject,"Name").c_str());
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
					strQuery = (L"Select * from Win32_NetworkAdapter where (Netconnectionstatus = 2)");
					hRes = pWbemServices->ExecQuery(_bstr_t("WQL"), strQuery,WBEM_FLAG_RETURN_IMMEDIATELY,NULL,&pEnumObject);
					if(hRes == S_OK)
					{
						ULONG uCount = 1, uReturned;
						IWbemClassObject * pClassObject = NULL;
						hRes = pEnumObject->Reset();
						if(hRes == S_OK)
						{
							while( pEnumObject->Next( WBEM_INFINITE, 
								uCount, &pClassObject, &uReturned) == S_OK )
							{
								tstring str;
								str =_getWmiInfo(pClassObject,"MACAddress");
								if (!str.empty())
								{
									str =_getWmiInfo(pClassObject,"PNPDeviceID");
									size_t pos =  str.find("PCI",0);
									if (pos != tstring::npos)
									{
										tstring str = _getWmiInfo(pClassObject,"Caption");
										size_t pos = str.find(']');
										if (pos != tstring::npos)
											str = str.substr(pos+1);
										strtmp = "网卡名称: "+str + "\r\n";
										SysInfo = SysInfo + strtmp;
										m_pLogger->WriteLog(LM_INFO,  "网卡名称: %s" , str.c_str()) ;	
									}
								}
							}
							if (pClassObject != NULL)
								pClassObject->Release();				
						}
					}
				}
			}
			if (pIWbemLocator)
				pIWbemLocator->Release();
			if (pWbemServices)
				pWbemServices->Release();
			if (pEnumObject)
				pEnumObject->Release();
		}
		CoUninitialize();
		if (!SysInfo.empty())
		{
			m_SysInfo = SysInfo;
		}
		return SysInfo;
	}
Beispiel #26
0
HRESULT
ExecuteMethodsInClass(
    __in     IWbemServices* WbemServices,
    __in_opt PWCHAR UserId,
    __in_opt PWCHAR Password,
    __in_opt PWCHAR DomainName
    )

/*++

Routine Description:

    This routine enumerates the instances of the Toaster method class and
    executes the methods in the class for each instance.

Arguments:

    WbemServices - Pointer to the WBEM services interface used for accessing
        the WMI services.

    UserId - Pointer to the user id information or NULL.

    Password - Pointer to password or NULL. If the user id is not specified,
        this parameter is ignored.

    DomainName - Pointer to domain name or NULL. If the user id is not specified,
        this parameter is ignored.

Return Value:

    HRESULT Status code.

--*/

{
    HRESULT status = S_OK;

    IEnumWbemClassObject* enumerator  = NULL;
    IWbemClassObject* classObj        = NULL;
    IWbemClassObject* instanceObj     = NULL;

    const BSTR className   = SysAllocString(TOASTER_METHOD_CLASS);

    VARIANT pathVariable;
    _bstr_t instancePath;
    ULONG   nbrObjsSought = 1;
    ULONG   nbrObjsReturned;

    //
    // Create an Enumeration object to enumerate the instances of the given class.
    //
    status = WbemServices->CreateInstanceEnum(className,
                                              WBEM_FLAG_SHALLOW | WBEM_FLAG_RETURN_IMMEDIATELY | WBEM_FLAG_FORWARD_ONLY,
                                              NULL,
                                              &enumerator);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Set authentication information for the interface.
    //
    status = SetInterfaceSecurity(enumerator, UserId, Password, DomainName);
    if (FAILED(status)) {
        goto exit;
    }

    //
    // Get the class object for the method definition.
    //
    status = WbemServices->GetObject(className, 0, NULL, &classObj, NULL);
    if (FAILED(status)) {
        goto exit;
    }

    do {

        //
        // Get the instance object for each instance of the class.
        //
        status = enumerator->Next(WBEM_INFINITE,
                                  nbrObjsSought,
                                  &instanceObj,
                                  &nbrObjsReturned);

        if (status == WBEM_S_FALSE) {
            status = S_OK;
            break;
        }

        if (FAILED(status)) {
            if (status == WBEM_E_INVALID_CLASS) {
                printf("ERROR: Toaster driver may not be active on the system.\n");
            }
            goto exit;
        }

        //
        // To obtain the object path of the object for which the method has to be
        // executed, query the "__PATH" property of the WMI instance object.
        //
        status = instanceObj->Get(_bstr_t(L"__PATH"), 0, &pathVariable, NULL, NULL);
        if (FAILED(status)) {
            goto exit;
        }

        instancePath = pathVariable.bstrVal;
        instanceObj->Release();
        instanceObj = NULL;

        //
        // Execute the methods in this instance of the class.
        //
        status = ExecuteMethod1InInstance(WbemServices, classObj, instancePath, IN_DATA1_VALUE);
        if (FAILED(status)) {
            goto exit;
        }

        status = ExecuteMethod2InInstance(WbemServices, classObj, instancePath, IN_DATA1_VALUE, IN_DATA2_VALUE);
        if (FAILED(status)) {
            goto exit;
        }

        status = ExecuteMethod3InInstance(WbemServices, classObj, instancePath, IN_DATA1_VALUE, IN_DATA2_VALUE);
        if (FAILED(status)) {
            goto exit;
        }
    } while (!FAILED(status));

exit:

    if (className != NULL) {
        SysFreeString(className);
    }

    if (classObj != NULL) {
        classObj->Release();
    }

    if (enumerator != NULL) {
        enumerator->Release();
    }

    if (instanceObj != NULL) {
        instanceObj->Release();
    }

    return status;
}
Beispiel #27
0
bool WMIVideoInfo::_queryPropertyWMI( const PVIQueryType queryType, const U32 adapterId, String *outValue )
{
   if( mServices == NULL )
      return false;

   BSTR bstrWQL  = SysAllocString(L"WQL");
   BSTR bstrPath = SysAllocString(L"select * from Win32_VideoController");
   IEnumWbemClassObject* enumerator;
   
   // Use the IWbemServices pointer to make requests of WMI
   HRESULT hr = mServices->ExecQuery(bstrWQL, bstrPath, WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator);

   if( FAILED( hr ) )
      return false;

   IWbemClassObject *adapter = NULL;   
   ULONG uReturned;

   // Get the appropriate adapter.
   for ( S32 i = 0; i <= adapterId; i++ )
   {
      hr = enumerator->Next(WBEM_INFINITE, 1, &adapter, &uReturned );

      if ( FAILED( hr ) || uReturned == 0 )
      {
         enumerator->Release();
         return false;         
      }
   }

   // Now get the property
   VARIANT v;
   hr = adapter->Get( smPVIQueryTypeToWMIString[queryType], 0, &v, NULL, NULL );

   bool result = SUCCEEDED( hr );

   if ( result )
   {
      switch( v.vt )
      {
      case VT_I4:
         {
            LONG longVal = v.lVal;

            if( queryType == PVI_VRAM )
               longVal = longVal >> 20; // Convert to megabytes

            *outValue = String::ToString( (S32)longVal );
            break;
         }

      case VT_UI4:
         {
            *outValue = String::ToString( (U32)v.ulVal );
            break;
         }

      case VT_BSTR:
         {
            *outValue = String( v.bstrVal );
            break;
         }            
      case VT_LPSTR:
      case VT_LPWSTR:
         break;
      }


   }                  

   // Cleanup      
   adapter->Release();   
   enumerator->Release();

   return result;
}
// **************************************************************************
//
//	CAdvClientDlg::OnEnumdisks()
//
// Description:
//		Enumerates all the disks on a machine. Demonstrates getting
//		known properties directly.
//
// Parameters:
//		None.
//
// Returns:
//		Nothing.
//
// Globals accessed:
//		None.
//
// Globals modified:
//		None.
//
//===========================================================================
void CAdvClientDlg::OnEnumdisks() 
{
	// these are for enumerating.
	HRESULT  hRes;
	ULONG uReturned;
	IWbemClassObject *pStorageDev = NULL;
	IEnumWbemClassObject *pEnumStorageDevs = NULL;

	// these help get properties.
	VARIANT pVal;
	BSTR propName = NULL;
    CString buf;

	// here's what we're looking for.
	// NOTE: make sure you specify a class that has a Provider()
	//	specified for it in the mof file. All other classes are
	//	abstract and wont be found using HMM_FLAG_SHALLOW. They
	//	will be found using HMM_FLAG_DEEP.
	BSTR className = SysAllocString(L"Win32_LogicalDisk");
	if (!className)
	{		
		TRACE(_T("SysAllocString failed: not enough memory\n"));
		return;
	}

	// setup for the "__RELPATH" system property.
	propName = SysAllocString(L"__RELPATH");
	if (!propName)
	{		
		SysFreeString(className);
		TRACE(_T("SysAllocString failed: not enough memory\n"));
		return;
	}

	VariantInit(&pVal);

	m_outputList.ResetContent();
	m_outputList.AddString(_T("working..."));

	TRACE(_T("Going for class\n"));

	//---------------------------
	// get the list of logical storage devices.
    if ((hRes = m_pIWbemServices->CreateInstanceEnum(className,
												WBEM_FLAG_SHALLOW, 
												NULL,
												&pEnumStorageDevs)) == S_OK) 
	{
		TRACE(_T("good enumerator\n"));

		m_outputList.ResetContent();

		uReturned = 1;
		while(uReturned == 1)
		{
			//---------------------------
			// enumerate through the resultset.
			hRes = pEnumStorageDevs->Next(TIMEOUT,
										1,
										&pStorageDev,
										&uReturned);

			TRACE(_T("Next() %d:%s\n"), uReturned, ErrorString(hRes));

			// was one found?
			if((hRes == S_OK) && (uReturned == 1))
			{

				TRACE(_T("Got a device class\n"));

				VariantClear(&pVal);

			
				// Add the path
				if (pStorageDev->Get(propName, 
										0L, 
										&pVal, 
										NULL, NULL) == S_OK) 
				{
					TRACE(_T("Got a device path\n"));
					 buf = V_BSTR(&pVal);
				} 

				// add to the output listbox.
				m_outputList.AddString(buf);

				// cleanup for next loop
				VariantInit(&pVal);

				// Done with this object.
				if (pStorageDev)
				{ 
					pStorageDev->Release();

					// NOTE: pStorageDev MUST be set to NULL for the next all to Next().
					pStorageDev = NULL;
				} 

			} // endif (hRes == S_OK)

        } // endwhile

		TRACE(_T("done enumming: %s\n"), ErrorString(hRes));

		// Done with this enumerator.
		if (pEnumStorageDevs)
		{ 
			pEnumStorageDevs->Release(); 
			pEnumStorageDevs = NULL;
		}
    } 
	else // CreateInstanceEnum() failed.
	{
		TRACE(_T("CreateInstanceEnum() failed: %s\n"), ErrorString(hRes));

	} // endif CreateInstanceEnum()

	TRACE(_T("returning\n"));
}
Beispiel #29
0
int wmi_get_battery_info() {

	std::cout << "wmi_get_battery_info" << std::endl;

	//assert(_initialized);
	//assert(pcpu_load_comp);
	//assert(pcpu_load_user);
	//assert(pcpu_load_sys);

	//float& cpu_load_comp = *pcpu_load_comp;
	//float& cpu_load_user = *pcpu_load_user;
	//float& cpu_load_sys = *pcpu_load_sys;

	IEnumWbemClassObject* enumerator = 0;
	IWbemClassObject* object = 0;

	//cpu_load_comp = 0;
	//cpu_load_user = 0;

	bool user_logged = false;

	long long current_process_id = _current_process_id;

	
	enumerator = request(
		// uint16, uint32, uint16, uint32... 
		bstr_t("SELECT"
		" Availability, BatteryRechargeTime, BatteryStatus,"
		"Caption, DesignCapacity, DesignVoltage, FullChargeCapacity"
		" FROM  Win32_Battery")
	);
		
	
	ULONG uReturn;
	for(;;) {
		
		HRESULT result = enumerator->Next(WBEM_INFINITE, 1, &object, &uReturn);
		if(0 == uReturn) {
			break;
		}

		VARIANT var;
		VariantInit(&var);
		result = object->Get(L"Voltage", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned short v = var.uiVal;
			//std::cout << "Availability: " << v << std::endl; 
		}
		
		VariantInit(&var);
		result = object->Get(L"DischargeRate", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "BatteryRechargeTime: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"Caption", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "BatteryRechargeTime: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"DesignCapacity", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "DesignCapacity: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"DesignVoltage", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned long long v = var.ullVal;
			//std::cout << "DesignVoltage: " << v << std::endl; 
		}

		VariantInit(&var);
		result = object->Get(L"FullChargeCapacity", 0, &var, NULL, NULL );
		
		if (SUCCEEDED(result)) {
			Print(std::wcout, var);
			//unsigned int v = var.uiVal;
			//std::cout << "FullChargeCapacity: " << v << std::endl; 
		}


		object->Release();
	} // for(;;)

	if (enumerator)
		enumerator->Release();

	return 0;	

}
Beispiel #30
-1
bool 
IPodDetector::doesIpodExist(IPod *ipod)
{
    IEnumWbemClassObject* enumerator = NULL;
    std::stringstream output;

    for( size_t i = 0; i < ipod->serial().length(); ++i )
    {
        output << (char)ipod->serial().c_str()[i];
    }
    queryByDeviceID( output.str(), &enumerator );
    
    IWbemClassObject* object;
    ULONG count;

    enumerator->Next( WBEM_INFINITE, 1, &object, &count );
    
    enumerator->Release();

    if( count > 0 )
    {
        object->Release();
        return true;
    }
    return false;
}