經過WMI接口監控服務器性能

WMI 是微軟操做系統的一個內置的組件,經過使用WMI咱們能夠獲取服務器硬件信息、收集服務器性能數據、操做Windows服務,甚至能夠遠程關機或是重啓服務器。編程

1、在C#編程中使用WMI服務器

要想在C#程序中使用WMI,必須添加System.Management.dll的引用,並使用System.Management命名空間。該命名空間提供對一組符合WMI基礎結構的系統、設備和應用程序的管理信息和管理事件的訪問。這裏介紹一下經常使用的幾個類:性能

ManagementScope用以鏈接WMI命名空間。spa

ManagementBaseObject包含管理對象的基本元素。操作系統

ManagementObject表示WMI實例。code

ManagementObjectCollection表示經過WMI檢索到的管理對象的集合。對象

ManagementObjectSearcher表示基於指定的查詢檢索管理對象的集合。該類也是用於檢索管理信息的較爲經常使用的入口點之一。blog

本人在寫代碼時將本身經常使用的一些關於WMI的基本操做進行了簡單的包裝。事件

1.ManagementScope內存

 1     public ManagementScope GetManagementScope()
 2     {
 3         if (_managementScope == null)
 4         {
 5             if (Environment.MachineName.ToLower() == ServerName.ToLower())
 6             {
 7                 _managementScope = new ManagementScope("\\\\" + ServerIP + "\\root\\cimv2");
 8             }
 9             else if (UserName != null && UserName.Length > 0)
10             {
11                 ConnectionOptions connectionOptions = new ConnectionOptions();
12                 connectionOptions.Username = UserName;
13                 connectionOptions.Password = Password;
14                 _managementScope = new ManagementScope("\\\\" + ServerIP + "\\root\\cimv2", connectionOptions);
15             }
16             else
17             {
18                 throw new ManagementException();
19             }
20         }
21         return _managementScope;
22     }

2.ManagementObjectSearcher

1     private ManagementObjectSearcher GetManagementObjectSearcher(string wql)
2     {
3         return new ManagementObjectSearcher(GetManagementScope(), new SelectQuery(wql));
4     }

3.獲得ManagementBaseObject集合

 1     public List<ManagementBaseObject> GetManagementObjects(string wql)
 2     {
 3         List<ManagementBaseObject> managementObjects = new List<ManagementBaseObject>();
 4         ManagementObjectCollection collection = GetManagementObjectCollection(wql);
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             managementObjects.Add(managementObject);
 8         }
 9         return managementObjects;
10     }

4.獲取系統信息

1     public object GetSystemInfo(ManagementBaseObject managementObject, string type)
2     {
3         return managementObject[type];
4     }
5     public object GetSystemInfo(string wql, string type)
6     {
7         return GetSystemInfo(GetManagementObjects(wql)[0], type);
8     }

有了這些基本操做做爲基礎,咱們就來看一下如何方便的獲取CPU、內存、硬盤等基本信息。

2、CPU

1.CPU型號

1     public string Model()
2     {
3         return GetSystemInfo("SELECT * FROM Win32_Processor", "Name").ToString().Trim();
4     }

2.獲取CPU個數

1     public int Number()
2     {
3         return GetManagementObjects("SELECT * FROM Win32_Processor").Count;
4     }

3.CPU使用率

 1     public int AverageLoadPercentage()
 2     {
 3         int loadPercentage = 0;
 4         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_Processor");
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             object load = GetSystemInfo(managementObject, "LoadPercentage");
 8             if (load == null)
 9             {
10                 load = 0;
11             }
12             loadPercentage += Int32.Parse(load.ToString());
13         }
14         return loadPercentage / collection.Count;
15     }

3、內存

1.總內存數

 1     public string TotalSize()
 2     {
 3         float size = 0;
 4         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_OperatingSystem");
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             size += long.Parse(GetSystemInfo(managementObject, "TotalVisibleMemorySize").ToString());
 8         }
 9         return (size / 1024).ToString("0.00") + "MB";
10     }

2.剩餘內存數

 1     public string FreeSize()
 2     {
 3         float size = 0;
 4         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_OperatingSystem");
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             size += float.Parse(GetSystemInfo(managementObject, "FreePhysicalMemory").ToString());
 8         }
 9         return (size / 1024).ToString("0.00") + "MB";
10     }

4、硬盤

1.定義邏輯硬盤結構

 1     public struct LogicalDisk
 2     {
 3         private string _deviceID;
 4         private long _size;
 5         private long _freeSize;
 6 
 7         public string Size
 8         {
 9             get
10             {
11                 return ((float) _size / 1024 / 1024 / 1024).ToString("0.00") + "GB";
12             }
13         }
14 
15         public string FreeSize
16         {
17             get
18             {
19                 return ((float) _freeSize / 1024 / 1024 / 1024).ToString("0.00") + "GB";
20             }
21         }
22 
23         public LogicalDisk(string deviceID, long size, long freeSize)
24         {
25             _deviceID = deviceID;
26             _size = size;
27             _freeSize = freeSize;
28         }
29     }

2.獲取邏輯硬盤信息

 1     private void GetLogicalDisk()
 2     {
 3         List<ManagementBaseObject> collection = GetManagementObjects("SELECT * FROM Win32_LogicalDisk WHERE DriveType = " + (int)System.IO.DriveType.Fixed);
 4 
 5         foreach (ManagementObject managementObject in collection)
 6         {
 7             long size, freeSize;
 8             object managementObjectInfo;
 9             managementObjectInfo = GetSystemInfo(managementObject, "Size");
10             if (managementObjectInfo == null)
11             {
12                 continue;
13             }
14             else
15             {
16                 size = long.Parse(GetSystemInfo(managementObject, "Size").ToString());
17             }
18             managementObjectInfo = GetSystemInfo(managementObject, "FreeSpace");
19             if (managementObjectInfo == null)
20             {
21                 freeSize = 0;
22             }
23             else
24             {
25                 freeSize = long.Parse(GetSystemInfo(managementObject, "FreeSpace").ToString());
26             }
27             string deviceID = GetSystemInfo(managementObject, "deviceid").ToString();
28             _logicalDisks.Add(new LogicalDisk(deviceID, size, freeSize));
29         }
30     }

5、Windows服務

1.兩個輔助方法

1     private ManagementObject GetServiceObject()
2     {
3         return GetManagementObjects("SELECT * FROM Win32_Service WHERE Name = '" + Name + "'")[0] as ManagementObject;
4     }
5 
6     private object GetManagementObjectInfo(string type)
7     {
8         return GetSystemInfo(GetServiceObject(), type);
9     }

2.服務運行情況

1     public string Status()
2     {
3         return GetManagementObjectInfo("State") as string;
4     }

3.啓動服務

 1     public bool Start()
 2     {
 3         try
 4         {
 5             if (Status() == "Stopped")
 6             {
 7                 GetServiceObject().InvokeMethod("StartService", null);
 8                 while (Status() == "Start Pending") ;
 9                 return true;
10             }
11             return false;
12         }
13         catch (Exception e)
14         {
15             throw new Exception(Name + "服務啓動失敗", e);
16         }
17     }

4.中止服務

 1     public bool AcceptStop()
 2     {
 3         return (bool)GetManagementObjectInfo("AcceptStop");
 4     }
 5     
 6     public bool Stop()
 7     {
 8         try
 9         {
10             if (AcceptStop())
11             {
12                 GetServiceObject().InvokeMethod("StopService", null);
13                 while (Status() == "Stop Pending") ;
14                 return true;
15             }
16             return false;
17         }
18         catch (Exception e)
19         {
20             throw new Exception(Name + "服務中止失敗", e);
21         }
22     }
相關文章
相關標籤/搜索