主机性能监控之wmi 获取系统信息及内存性能信息

欢迎转帖 请保持文本完整并注明出处

 

这里参考了http://www.cnblogs.com/lxcsmallcity/archive/2009/10/11/1580803.html 

使用了PYTHON 和 vc 进行了调用WMI的代码编写

通过搜索和查看MSDN 可以找到WMI的基本用法

其实主要是WMI接口的初始化 使用 释放的过程

然后就是查找MSDN各个Win32_OperatingSystem  Win32_Process等的结构的说明 进行相关信息的获取

这里先介绍Win32_OperatingSystem的用法

Win32_OperatingSystem结构(来自MSDN)

class Win32_OperatingSystem : CIM_OperatingSystem
{
  string BootDevice;
  string BuildNumber;
  string BuildType;
  string Caption;
  string CodeSet;
  string CountryCode;
  string CreationClassName;
  string CSCreationClassName;
  string CSDVersion;
  string CSName;
  sint16 CurrentTimeZone;
  boolean DataExecutionPrevention_Available;
  boolean DataExecutionPrevention_32BitApplications;
  boolean DataExecutionPrevention_Drivers;
  uint8 DataExecutionPrevention_SupportPolicy;
  boolean Debug;
  string Description;
  boolean Distributed;
  uint32 EncryptionLevel;
  uint8 ForegroundApplicationBoost;
  uint64 FreePhysicalMemory;
  uint64 FreeSpaceInPagingFiles;
  uint64 FreeVirtualMemory;
  datetime InstallDate;
  uint32 LargeSystemCache;
  datetime LastBootUpTime;
  datetime LocalDateTime;
  string Locale;
  string Manufacturer;
  uint32 MaxNumberOfProcesses;
  uint64 MaxProcessMemorySize;
  string MUILanguages[];
  string Name;
  uint32 NumberOfLicensedUsers;
  uint32 NumberOfProcesses;
  uint32 NumberOfUsers;
  uint32 OperatingSystemSKU;
  string Organization;
  string OSArchitecture;
  uint32 OSLanguage;
  uint32 OSProductSuite;
  uint16 OSType;
  string OtherTypeDescription;
  Boolean PAEEnabled;
  string PlusProductID;
  string PlusVersionNumber;
  boolean Primary;
  uint32 ProductType;
  uint8 QuantumLength;
  uint8 QuantumType;
  string RegisteredUser;
  string SerialNumber;
  uint16 ServicePackMajorVersion;
  uint16 ServicePackMinorVersion;
  uint64 SizeStoredInPagingFiles;
  string Status;
  uint32 SuiteMask;
  string SystemDevice;
  string SystemDirectory;
  string SystemDrive;
  uint64 TotalSwapSpaceSize;
  uint64 TotalVirtualMemorySize;
  uint64 TotalVisibleMemorySize;
  string Version;
  string WindowsDirectory;
};

初始化WMI 连接 查询其中各个元素就可以获取信息

代码如下:

// WMI_Sample.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <atlstr.h>
#include <comutil.h>
#include <comdef.h>  
#include <Wbemidl.h>  

using namespace std;

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



//===================================================
class CMyWMI{
    IWbemLocator *pLoc_;  
    IWbemServices *pSvc_;  

    void GetInfo(WCHAR* wszQueryInfo,IWbemClassObject *pclsObj);
public:
    CMyWMI():pLoc_(NULL),pSvc_(NULL){}
    ~CMyWMI(){ ClearWMI(); }
    bool InitWMI();
    bool ClearWMI();
    bool QuerySystemInfo();

};


void CMyWMI::GetInfo(WCHAR* wszQueryInfo,IWbemClassObject *pclsObj)
{
    if(wszQueryInfo == NULL || NULL == pclsObj)
        return;
    VARIANT vtProp;  
    char* lpszText = NULL;

    HRESULT hr = pclsObj->Get(wszQueryInfo, 0, &vtProp, 0, 0);  
    lpszText = _com_util::ConvertBSTRToString(V_BSTR(&vtProp));
    printf_s("%s\n", lpszText);

    delete[] lpszText;
    VariantClear(&vtProp); 
}


bool CMyWMI::QuerySystemInfo()
{
    HRESULT hres; //定义COM调用的返回  
    IEnumWbemClassObject* pEnumerator = NULL;  
    bool bRet = false;

    try{
        hres = pSvc_->ExecQuery(  
            bstr_t("WQL"),     
            bstr_t("SELECT * FROM Win32_OperatingSystem"),  
            WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,   
            NULL,  
            &pEnumerator);  

        if (FAILED(hres))  
        {  
            throw exception("ExecQuery() error.");
        }  

        while (pEnumerator)  
        {
            IWbemClassObject *pclsObj;  
            ULONG uReturn = 0;  

            HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,   
                &pclsObj, &uReturn);  
            if(0 == uReturn)  
            {  
                break;  
            }  
        
            GetInfo(L"BootDevice",pclsObj);
            GetInfo(L"Caption",pclsObj);
            GetInfo(L"Manufacturer",pclsObj);
            GetInfo(L"CSName",pclsObj);
            GetInfo(L"WindowsDirectory",pclsObj);
            GetInfo(L"SystemDirectory",pclsObj);
            GetInfo(L"TotalVisibleMemorySize",pclsObj);
            GetInfo(L"FreePhysicalMemory",pclsObj);

            pclsObj->Release(); 
        }
    

    }catch(exception& e)
    {
        cout << e.what() << endl;
        if(pEnumerator != NULL)
        {
            pEnumerator->Release(); 
            pEnumerator = NULL;
        }
        return bRet;
    }

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

    bRet = true;
    return bRet;
}


bool CMyWMI::ClearWMI()
{    
    bool bRet = false;

    if( NULL != pSvc_)
        pSvc_->Release();  

    if(pLoc_ != NULL )
        pLoc_->Release();


    CoUninitialize();
    bRet = true;
    return bRet;
}



bool CMyWMI::InitWMI()
{
    HRESULT hres; //定义COM调用的返回  
    bool bRet = false;

    try{
        hres =  CoInitializeEx(0, COINIT_MULTITHREADED);   
        if (FAILED(hres))  
        {  
            throw exception("CoInitializeEx() error.");
        }  

        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))  
        {  
            throw exception("CoInitializeEx() error."); 
        }  

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

        if (FAILED(hres))  
        {  
            throw exception("CoCreateInstance() error."); 
        }  

        // 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))  
        {  
            throw exception("ConnectServer() error."); 
        }

        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))  
        {  
            throw exception("CoSetProxyBlanket() error.");
        }  


    }catch(exception& e)
    {
        cout << e.what() << endl;
        return bRet;
    }
    
    bRet = true;
    return bRet;
}

//=========================================================
int _tmain(int argc, _TCHAR* argv[])
{
    CMyWMI myWMI;
        
    myWMI.InitWMI();
    myWMI.QuerySystemInfo();

    return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值