C#伺服器效能監控之WMI的程式碼範例詳解

來源:互聯網
上載者:User

1.WMI簡介

WMI是英文Windows Management Instrumentation的簡寫,通過使用WMI,我們可以擷取本地或遠程伺服器的績效參數和進程運行情況,以及大部分硬體資訊,但前提是啟動並執行使用者要有足夠的許可權,如administrator組使用者等。這也是做負載平衡所需要且比較方便快捷的途徑。

2.使用時首先添加System.Management.dll,然後引用

using System.Management;

3.定義遠端存取

public class ManagementConnectPool    ...{        private static System.Management.ConnectionOptions Conn = new ConnectionOptions() ;        private static ManagementObjectSearcher mos = new ManagementObjectSearcher();        private string username = "";        private string pwd = "";        private string space="";        private string server = "";        public ManagementConnectPool(string mpusername,string mppwd , string mpspace ,string mpserver)        ...{            this.username = mpusername;            this.pwd = mppwd;            this.space = mpspace;            this.server = mpserver;            Conn.Username = mpusername;            Conn.Password = mppwd;            string scopestring ="//" + mpserver + mpspace;            System.Management.ManagementScope Ms = new ManagementScope(scopestring);            Ms.Connect();            mos.Scope = Ms;        }        public ManagementObjectCollection getQueryResult(string queryString)        ...{            ObjectQuery oq = new ObjectQuery();            oq.QueryString = queryString;            mos.Query = oq;            ManagementObjectCollection moc =mos.Get();            return moc;        }    }

4.擷取CPU,記憶體,網路流量等資訊

public class Monitor    ...{         private string username = "";        private string pwd ="";        private string ip = "";        ManagementConnectPool mcp;        WMSServerClass server;                public Monitor(string username,string pwd,string ip)...{            this.username = username;            this.pwd = pwd ;            this.ip = ip;            mcp = new ManagementConnectPool(username,pwd,"/root/cimv2",ip);            server = new WMSServerClass();        }        WMI方式擷取網卡流量#region WMI方式擷取網卡流量        private void getNetWorkFlow()        ...{ManagementObjectCollection moc = mcp.getQueryResult(@"select * from Win32_NetworkAdapter where macaddress<>null and manufacturer<>'Microsoft'");            string[] list = new string[moc.Count] ;            foreach(System.Management.ManagementObject mymac in moc)             ...{                 string a =  mymac["Speed"].ToString();//null WMI未實現該屬性                Console.WriteLine(a.ToString());            }        }        #endregion                        WMI方式擷取CPU資訊#region WMI方式擷取CPU資訊        private void getCpuInfo()        ...{            ManagementObjectCollection moc = mcp.getQueryResult("select * from Win32_Processor");            string[] list = new string[moc.Count];            int i = 0;            foreach(ManagementObject mo  in moc)            ...{                    string total = mo.GetPropertyValue("LoadPercentage").ToString();                list[i]=total;                i++;            }        }        #endregion        WMI方式擷取記憶體使用量率#region WMI方式擷取記憶體使用量率        public string getMemoryUsage()        ...{ManagementObjectCollection moc = mcp.getQueryResult("select * from Win32_LogicalMemoryConfiguration");            int totalm = 1; int avilablem = 1;            foreach(ManagementObject mo  in moc)            ...{                string total = mo.GetPropertyValue("TotalPhysicalMemory").ToString();                totalm = int.Parse(total);            }            moc = mcp.getQueryResult("select * from Win32_PerfRawData_PerfOS_Memory");            foreach(ManagementObject mo  in moc)            ...{                string avilable = mo.GetPropertyValue("AvailableKBytes").ToString();                avilablem = int.Parse(avilable);            }            int usedm = totalm - avilablem;            double memoryusage = (double)usedm * (double)100 / (double)totalm ;            return memoryusage.ToString();        }        #endregion}

5.擷取本地機器資訊(WEB)

1.如何用WMI獲得指定磁碟的容量#region 1.如何用WMI獲得指定磁碟的容量         private string DriveType(string type)          ...{             string rtntype="";             switch (type)              ...{                 case "1":                     rtntype="Not Type";                     break;                 case "2":                     rtntype="Floppy disk";                     break;                 case "3":                     rtntype="Hard disk";                     break;                 case "4":                     rtntype="Removable drive or network drive";                     break;                 case "5":                     rtntype="CD-ROM";                     break;                 case "6":                     rtntype="RAM disk";                     break;                 default :                     break;             }             return rtntype;         }          private void Button1_Click(object sender, System.EventArgs e)          ...{             SelectQuery query=new SelectQuery("Select * From Win32_LogicalDisk");              ManagementObjectSearcher searcher=new ManagementObjectSearcher(query);              foreach(ManagementBaseObject disk in searcher.Get())               ...{ Response.Write(disk["Name"] +" "+DriveType(disk["DriveType"].ToString()) + " " + disk["VolumeName"]+"<br>");              }         }         #endregion           2.如何用WMI獲得指定磁碟的容量#region 2.如何用WMI獲得指定磁碟的容量         private void Button2_Click(object sender, System.EventArgs e)          ...{             ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid="c:"");              disk.Get();              Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");                      }         #endregion           3.如何列出機器中所有的共用資源#region 3.如何列出機器中所有的共用資源         private void Button3_Click(object sender, System.EventArgs e)          ...{             ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_share");              foreach (ManagementObject share in searcher.Get())               ...{                  Response.Write(share.GetText(TextFormat.Mof));              }          }         #endregion           4.怎樣寫程式控制制讓系統中的某個檔案夾共用或不共用#region 4.怎樣寫程式控制制讓系統中的某個檔案夾共用或不共用         private void Button4_Click(object sender, System.EventArgs e)          ...{              /**//*首先,這需要以有相應許可權的使用者登入系統才行             將              object[] obj = {"C:/Temp","我的共用",0,10,"Dot Net 實現的共用",""};              改為              object[] obj = {"C:/Temp","我的共用",0,null,"Dot Net 實現的共用",""};              就可以實現授權給最多使用者了。             */             ManagementClass _class = new ManagementClass(new ManagementPath("Win32_Share"));              object[] obj = ...{"C:/Temp","我的共用",0,10,"Dot Net 實現的共用",""};             _class.InvokeMethod("create",obj);          }         #endregion           5.如何獲得系統服務的運行狀態#region 5.如何獲得系統服務的運行狀態         private void Button5_Click(object sender, System.EventArgs e)          ...{             string[] lvData =  new string[4];                         ManagementObjectSearcher searcher =new ManagementObjectSearcher("SELECT * FROM Win32_Service");              foreach (ManagementObject mo in searcher.Get())               ...{                  lvData[0] = mo["Name"].ToString();                  lvData[1] = mo["StartMode"].ToString();                  if (mo["Started"].Equals(true))                      lvData[2] = "Started";                  else                      lvData[2] = "Stop";                  lvData[3] = mo["StartName"].ToString();                  Response.Write(lvData[0]+lvData[1]+lvData[2]+lvData[3]);                                 }                      }         #endregion           6.通過WMI修改IP,而實現不用重新啟動#region 6.通過WMI修改IP,而實現不用重新啟動         private void Button6_Click(object sender, System.EventArgs e)          ...{             ReportIP();              // SwitchToDHCP();              SwitchToprivate();              Thread.Sleep( 5000 );              ReportIP();              Response.Write( "end." );         }                          private void SwitchToDHCP()           ...{              ManagementBaseObject inPar = null;              ManagementBaseObject outPar = null;              ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");              ManagementObjectCollection moc = mc.GetInstances();              foreach( ManagementObject mo in moc )               ...{                  if( ! (bool) mo["IPEnabled"] )                      continue;                   inPar = mo.GetMethodParameters("EnableDHCP");                  outPar = mo.InvokeMethod( "EnableDHCP", inPar, null );                  break;              }          }           private void SwitchToprivate()           ...{              ManagementBaseObject inPar = null;              ManagementBaseObject outPar = null;              ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");              ManagementObjectCollection moc = mc.GetInstances();              foreach( ManagementObject mo in moc )               ...{                  if( ! (bool) mo[ "IPEnabled" ] )                      continue;                   inPar = mo.GetMethodParameters( "Enableprivate" );                   inPar["IPAddress"] = new string[] ...{ "192.168.1.1" };                   inPar["SubnetMask"] = new string[] ...{ "255.255.255.0" };                  outPar = mo.InvokeMethod( "Enableprivate", inPar, null );                  break;              }          }           private void ReportIP()           ...{              Response.Write( "****** Current IP addresses:" );              ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");              ManagementObjectCollection moc = mc.GetInstances();              foreach( ManagementObject mo in moc )               ...{                  if( ! (bool) mo[ "IPEnabled" ] )                      continue;                   string str="{0}  SVC: '{1}' MAC: [{2}]";                 str= string.Format(mo["Caption"].ToString(), mo["ServiceName"].ToString(),mo["MACAddress"].ToString());                  Response.Write(str);                   string[] addresses = (string[]) mo[ "IPAddress" ];                  string[] subnets = (string[]) mo[ "IPSubnet" ];                   Response.Write( " Addresses :" );                  foreach(string sad in addresses)                      Response.Write(sad+"<br>");                   Response.Write( " Subnets :" );                  foreach(string sub in subnets )                      Response.Write(sub+"<br>");              }          }         #endregion           7.如何利用WMI遠程重啟遠端電腦#region 7.如何利用WMI遠程重啟遠端電腦         private void Button7_Click(object sender, System.EventArgs e)          ...{             Response.Write("Computer details retrieved using Windows Management Instrumentation (WMI)");              Response.Write("mailto:singlepine@hotmail.com");              Response.Write("=========================================================================");               //串連遠端電腦              ConnectionOptions co = new ConnectionOptions();              co.Username = "john";              co.Password = "john";              System.Management.ManagementScope ms = new System.Management.ManagementScope("//192.168.1.2/root/cimv2", co);                    //查詢遠端電腦              System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");                                  ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms,oq);              ManagementObjectCollection queryCollection1 = query1.Get();                          foreach( ManagementObject mo in queryCollection1 )                ...{                   string[] ss=...{""};                  mo.InvokeMethod("Reboot",ss);                  Response.Write(mo.ToString());              }          }         #endregion           8.利用WMI建立一個新的進程#region 8.利用WMI建立一個新的進程         private void Button8_Click(object sender, System.EventArgs e)          ...{             //Get the object on which the method will be invoked              ManagementClass processClass = new ManagementClass("Win32_Process");               //Get an input parameters object for this method              ManagementBaseObject inParams = processClass.GetMethodParameters("Create");               //Fill in input parameter values              inParams["CommandLine"] = "calc.exe";               //Execute the method              ManagementBaseObject outParams = processClass.InvokeMethod ("Create", inParams, null);               //Display results              //Note: The return code of the method is provided in the "returnvalue" property of the outParams object              Response.Write("Creation of calculator process returned: " + outParams["returnvalue"]);              Response.Write("Process ID: " + outParams["processId"]);           }         #endregion           9.如何通過WMI終止一個進程#region 9.如何通過WMI終止一個進程         private void Button9_Click(object sender, System.EventArgs e)          ...{             ManagementObject service =                   new ManagementObject("win32_service="winmgmt"");              InvokeMethodOptions options = new InvokeMethodOptions();              options.Timeout = new TimeSpan(0,0,0,5);                ManagementBaseObject outParams = service.InvokeMethod("StopService", null, options);              Response.Write("Return Status = " + outParams["Returnvalue"]);         }         #endregion           10.如何用WMI 來擷取遠程機器的目錄以及檔案#region 10.如何用WMI 來擷取遠程機器的目錄以及檔案         private void Button10_Click(object sender, System.EventArgs e)          ...{             ManagementObject disk = new ManagementObject(                  "win32_logicaldisk.deviceid="c:"");              disk.Get();              Response.Write("Logical Disk Size = " + disk["Size"] + " bytes");         }         #endregion           11.網卡的MAC地址#region 11.網卡的MAC地址         private void Button11_Click(object sender, System.EventArgs e)          ...{             ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");              ManagementObjectCollection moc = mc.GetInstances();              foreach(ManagementObject mo in moc)               ...{                  if((bool)mo["IPEnabled"] == true)                      Response.Write("MAC address"+mo["MacAddress"].ToString()+"<br>");                  mo.Dispose();              }          }         #endregion           12.CPU的系列號#region 12.CPU的系列號          private void Button12_Click(object sender, System.EventArgs e)          ...{             string cpuInfo = "";//cpu序號              ManagementClass cimobject = new ManagementClass("Win32_Processor");              ManagementObjectCollection moc = cimobject.GetInstances();              foreach(ManagementObject mo in moc)               ...{                  cpuInfo = mo.Properties["ProcessorId"].Value.ToString();                  Response.Write(cpuInfo);             }          }         #endregion           13.主板的系列號#region 13.主板的系列號         private void Button13_Click(object sender, System.EventArgs e)          ...{             ManagementObjectSearcher searcher=new ManagementObjectSearcher("SELECT * FROM Win32_BaseBoard");             foreach(ManagementObject share in searcher.Get())              ...{                 Response.Write("主板製造商:" + share["Manufacturer"].ToString()) ;                 Response.Write("型號:" +share["Product"].ToString()) ;                 Response.Write("序號:"+share["SerialNumber"].ToString()) ;             }         }         #endregion           14.擷取硬碟ID#region 14.擷取硬碟ID         private void Button14_Click(object sender, System.EventArgs e)          ...{             String HDid;              ManagementClass cimobject = new ManagementClass("Win32_DiskDrive");              ManagementObjectCollection moc = cimobject.GetInstances();              foreach(ManagementObject mo in moc)               ...{                  HDid = (string)mo.Properties["Model"].Value;                  Response.Write(HDid);               }          }         #endregion           15.擷取原生使用者列表#region 15.擷取原生使用者列表         private void Button15_Click(object sender, System.EventArgs e)          ...{             SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");             ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);             foreach(ManagementObject os in searcher.Get())              ...{                 Response.Write(os["Name"]);             }         }         #endregion     }


通過上面介紹的方法,可以很輕鬆的擷取遠程或本地機器的效能,進程和硬體資訊等。另外:WMI也可以通過使用Vbscript等指令碼調用。

說明:其中部分資源來自網友小山的blog。但不夠詳細說明WMI在伺服器效能方面的能力!

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.