C#实现对远程服务器的内存和CPU监控
作者:大白的记事本 发布时间:[ 2016/7/5 10:13:11 ] 推荐标签:服务器 .NET 内存
1、 主要使用到的组件有System.Management.dll
2、 主要类为 :ManagementScope
连接远程服务器示例代码:
1 private const string PROPERTY_CAPACITY = "Capacity";
2 private const string PROPERTY_AVAILABLE_BYTES = "AvailableBytes";
3 private const string PROPERTY_PROCESS_ID = "ProcessId";
4 private const string PROPERTY_PROCESS_NAME = "Name";
5 private const string PROPERTY_WORKING_SET_SIZE = "WorkingSetSize";
6
7
8 ConnectionOptions Conn = new ConnectionOptions();
9 //设定用于WMI连接操作的用户名
10 Conn.Username = "用户名";
11 //设定用户的口令
12 Conn.Password = "密码";
13 ManagementScope Ms = new ManagementScope("\\ip\root\cimv2", Conn);
14 Ms.Connect();
具体查询举例:
1 var query1 = new SelectQuery("SELECT * FROM Win32_PhysicalMemory");
2 var query2 = new SelectQuery("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");
3 var query3 = new SelectQuery("SELECT * FROM Win32_Processor");
4 var query4 = new SelectQuery("SELECT * FROM Win32_Process");
5
6 var searcher1 = new ManagementObjectSearcher(Ms, query1);
7 var searcher2 = new ManagementObjectSearcher(Ms, query2);
8 var searcher3 = new ManagementObjectSearcher(Ms, query3);
9 var searcher4 = new ManagementObjectSearcher(Ms, query4);
查询内存和CPU:
1 var capacity = 0.0;
2 var free = 0.0;
3 var cpu = 0.0;
4 // 2048
5 foreach (var o in searcher1.Get())
6capacity += (double)Convert.ToUInt64(o[PROPERTY_CAPACITY]) / (double)(1024 * 1024);
7 foreach (var o in searcher2.Get())
8 free += (double)Convert.ToUInt64(o[PROPERTY_AVAILABLE_BYTES]) / (double)(1024 * 1024);
9 foreach (var o in searcher3.Get())
10 {
11 if (o["LoadPercentage"] != null)
12 {
13 cpu = long.Parse(o["LoadPercentage"].ToString());
14 }
15 else {
16 cpu = 0;
17 }
18 }
举例远程重启某个进程(部分示例代码):
1 ConnectionOptions Conn = new ConnectionOptions();
2 Conn.Username = userName; //设定用户的口令
3 Conn.Password = pwd;
4 Ms = new ManagementScope("\\" + ip + "\root\cimv2", Conn);
5 Ms.Connect();
6 ManagementClass processClass = new ManagementClass(Ms, new ManagementPath("Win32_Process"), null);
7 //获得用来提供参数的对象
8 ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
9 //设定命令行参数
10 inParams["CommandLine"] = path;// @"需要启动的进程路径";
11 //执行程序
12 ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
Other、可以用程序操作批处理文件(.bat)来查询进程或者是关闭进程:
例如查询所有进程 :tasklist /S ip /U 用户名 /P 密码
关闭某个进程:
taskkill /S ip /U用户名/P 密码 /IM 需要关闭的进程名
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11