您好,欢迎访问一九零五行业门户网

C#服务器性能监控之WMI的代码示例详解

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在服务器性能方面的能力!
以上就是c#服务器性能监控之wmi的代码示例详解的详细内容。
其它类似信息

推荐信息