学编程 ❀(๑╯◡╰๑)❀ 就上soxunxi.cn!这里有CMS,CSS,NET,PHP,Linux,HTML,JAVA,MySQL,Python等教程.
当前位置: NET > C#服务器机能监控之WMI的代码示例详解【C#.Net教程】,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的代码示例详解的细致内容,更多请关注ki4网别的相干文章!

「梦想一旦被付诸行动,就会变得神圣,如果觉得我的文章对您有用,请帮助本站成长」

分享到:
赞(0) 打赏

支付宝扫一扫打赏

微信扫一扫打赏

上一篇:

下一篇:

相关推荐

0 条评论关于"C#服务器机能监控之WMI的代码示例详解【C#.Net教程】,C#,性能监控,WMI"

最新评论

    暂无留言哦~~

博客简介

看古风美女插画Cos小姐姐,素材合集图集打包下载:炫龙网,好看二次元插画应有尽有,唯美小姐姐等你来。

友情链接

他们同样是一群网虫,却不是每天泡在网上游走在淘宝和网游之间、刷着本来就快要透支的信用卡。他们或许没有踏出国门一步,但同学却不局限在一国一校,而是遍及全球!申请交换友链

服务热线:
 

 QQ在线交流

 旺旺在线