zoukankan      html  css  js  c++  java
  • 主机性能监控之wmi 获取系统信息及内存性能信息

    标 题: 主机性能监控之wmi 获取系统信息及内存性能信息
    作 者: itdef
    链 接: http://www.cnblogs.com/itdef/p/3990240.html 

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

    这里参考了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 连接 查询其中各个元素就可以获取信息

    代码如下:

      1 // WMI_Sample.cpp : 定义控制台应用程序的入口点。
      2 //
      3 
      4 #include "stdafx.h"
      5 #include <iostream>
      6 #include <iomanip>
      7 #include <atlstr.h>
      8 #include <comutil.h>
      9 #include <comdef.h>  
     10 #include <Wbemidl.h>  
     11 
     12 using namespace std;
     13 
     14 #pragma comment(lib, "wbemuuid.lib")  
     15 #pragma comment(lib, "comsuppw.lib")
     16 
     17 
     18 
     19 //===================================================
     20 class CMyWMI{
     21     IWbemLocator *pLoc_;  
     22     IWbemServices *pSvc_;  
     23 
     24     void GetInfo(WCHAR* wszQueryInfo,IWbemClassObject *pclsObj);
     25 public:
     26     CMyWMI():pLoc_(NULL),pSvc_(NULL){}
     27     ~CMyWMI(){ ClearWMI(); }
     28     bool InitWMI();
     29     bool ClearWMI();
     30     bool QuerySystemInfo();
     31 
     32 };
     33 
     34 
     35 void CMyWMI::GetInfo(WCHAR* wszQueryInfo,IWbemClassObject *pclsObj)
     36 {
     37     if(wszQueryInfo == NULL || NULL == pclsObj)
     38         return;
     39     VARIANT vtProp;  
     40     char* lpszText = NULL;
     41 
     42     HRESULT hr = pclsObj->Get(wszQueryInfo, 0, &vtProp, 0, 0);  
     43     lpszText = _com_util::ConvertBSTRToString(V_BSTR(&vtProp));
     44     printf_s("%s\n", lpszText);
     45 
     46     delete[] lpszText;
     47     VariantClear(&vtProp); 
     48 }
     49 
     50 
     51 bool CMyWMI::QuerySystemInfo()
     52 {
     53     HRESULT hres; //定义COM调用的返回  
     54     IEnumWbemClassObject* pEnumerator = NULL;  
     55     bool bRet = false;
     56 
     57     try{
     58         hres = pSvc_->ExecQuery(  
     59             bstr_t("WQL"),     
     60             bstr_t("SELECT * FROM Win32_OperatingSystem"),  
     61             WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,   
     62             NULL,  
     63             &pEnumerator);  
     64 
     65         if (FAILED(hres))  
     66         {  
     67             throw exception("ExecQuery() error.");
     68         }  
     69 
     70         while (pEnumerator)  
     71         {
     72             IWbemClassObject *pclsObj;  
     73             ULONG uReturn = 0;  
     74 
     75             HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,   
     76                 &pclsObj, &uReturn);  
     77             if(0 == uReturn)  
     78             {  
     79                 break;  
     80             }  
     81         
     82             GetInfo(L"BootDevice",pclsObj);
     83             GetInfo(L"Caption",pclsObj);
     84             GetInfo(L"Manufacturer",pclsObj);
     85             GetInfo(L"CSName",pclsObj);
     86             GetInfo(L"WindowsDirectory",pclsObj);
     87             GetInfo(L"SystemDirectory",pclsObj);
     88             GetInfo(L"TotalVisibleMemorySize",pclsObj);
     89             GetInfo(L"FreePhysicalMemory",pclsObj);
     90 
     91             pclsObj->Release(); 
     92         }
     93     
     94 
     95     }catch(exception& e)
     96     {
     97         cout << e.what() << endl;
     98         if(pEnumerator != NULL)
     99         {
    100             pEnumerator->Release(); 
    101             pEnumerator = NULL;
    102         }
    103         return bRet;
    104     }
    105 
    106     
    107     if(pEnumerator != NULL)
    108     {
    109         pEnumerator->Release(); 
    110         pEnumerator = NULL;
    111     }
    112 
    113     bRet = true;
    114     return bRet;
    115 }
    116 
    117 
    118 bool CMyWMI::ClearWMI()
    119 {    
    120     bool bRet = false;
    121 
    122     if( NULL != pSvc_)
    123         pSvc_->Release();  
    124 
    125     if(pLoc_ != NULL )
    126         pLoc_->Release();
    127 
    128 
    129     CoUninitialize();
    130     bRet = true;
    131     return bRet;
    132 }
    133 
    134 
    135 
    136 bool CMyWMI::InitWMI()
    137 {
    138     HRESULT hres; //定义COM调用的返回  
    139     bool bRet = false;
    140 
    141     try{
    142         hres =  CoInitializeEx(0, COINIT_MULTITHREADED);   
    143         if (FAILED(hres))  
    144         {  
    145             throw exception("CoInitializeEx() error.");
    146         }  
    147 
    148         hres =  CoInitializeSecurity(  
    149             NULL,   
    150             -1,                          // COM authentication  
    151             NULL,                        // Authentication services  
    152             NULL,                        // Reserved  
    153             RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication   
    154             RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation    
    155             NULL,                        // Authentication info  
    156             EOAC_NONE,                   // Additional capabilities   
    157             NULL                         // Reserved  
    158             );
    159 
    160         if (FAILED(hres))  
    161         {  
    162             throw exception("CoInitializeEx() error."); 
    163         }  
    164 
    165         hres = CoCreateInstance(  
    166             CLSID_WbemLocator,  
    167             0,   
    168             CLSCTX_INPROC_SERVER,   
    169             IID_IWbemLocator, (LPVOID *) &pLoc_);  
    170 
    171         if (FAILED(hres))  
    172         {  
    173             throw exception("CoCreateInstance() error."); 
    174         }  
    175 
    176         // to make IWbemServices calls.  
    177         hres = pLoc_->ConnectServer(  
    178             _bstr_t(L"ROOT\\CIMV2"), // Object path of WMI namespace  
    179             NULL,                    // User name. NULL = current user  
    180             NULL,                    // User password. NULL = current  
    181             0,                       // Locale. NULL indicates current  
    182             NULL,                    // Security flags.  
    183             0,                       // Authority (e.g. Kerberos)  
    184             0,                       // Context object   
    185             &pSvc_                    // pointer to IWbemServices proxy  
    186             );  
    187 
    188         if (FAILED(hres))  
    189         {  
    190             throw exception("ConnectServer() error."); 
    191         }
    192 
    193         hres = CoSetProxyBlanket(  
    194             pSvc_,                        // Indicates the proxy to set  
    195             RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx  
    196             RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx  
    197             NULL,                        // Server principal name   
    198             RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx   
    199             RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx  
    200             NULL,                        // client identity  
    201             EOAC_NONE                    // proxy capabilities   
    202             );  
    203 
    204         if (FAILED(hres))  
    205         {  
    206             throw exception("CoSetProxyBlanket() error.");
    207         }  
    208 
    209 
    210     }catch(exception& e)
    211     {
    212         cout << e.what() << endl;
    213         return bRet;
    214     }
    215     
    216     bRet = true;
    217     return bRet;
    218 }
    219 
    220 //=========================================================
    221 int _tmain(int argc, _TCHAR* argv[])
    222 {
    223     CMyWMI myWMI;
    224         
    225     myWMI.InitWMI();
    226     myWMI.QuerySystemInfo();
    227 
    228     return 0;
    229 }
    View Code

     python 代码:

    #!/usr/bin/env python 
    # -*- coding: cp936 -*-
     
    import wmi 
    import os 
    import sys 
    import platform 
    import time
    
    
    def sys_version():  
        c = wmi.WMI () 
        #获取操作系统版本 
        for sys in c.Win32_OperatingSystem(): 
            print "Version:%s" % sys.Caption.encode("UTF8"),"Vernum:%s" % sys.BuildNumber 
            print sys.OSArchitecture.encode("UTF8")#系统是32位还是64位的 
            print sys.NumberOfProcesses #当前系统运行的进程总数
            print sys.WindowsDirectory 
            print sys.SystemDirectory
            print "system total memory: " ,sys.TotalVisibleMemorySize
            print "system free memory: " ,sys.FreePhysicalMemory
    
    
    def main(): 
        sys_version() 
        
    if __name__ == '__main__': 
        main()
        #print platform.system() 
    View Code

     效果图

  • 相关阅读:
    javaapplicationWeb application setup on Ubuntu VPS
    内容中断随想录(risc cpu的那些事)
    算法线性编程珠玑读书笔记之----->使用线性算法求解连续子序列的最大和
    classnull100
    安装javaUbuntu下安装JDK1.6,并将之设为默认的JDK
    筛选实现C++实现筛选法
    调试设置移动端Web开发环境搭建实践
    路由器交换机[置顶] 路由器和交换机的综合实验⑵
    卡数字怀念的东西:魔方
    密码配置配置SSH免密码登陆
  • 原文地址:https://www.cnblogs.com/itdef/p/3990240.html
Copyright © 2011-2022 走看看