C#实现对远程服务器的内存和CPU监控

C#实现对远程服务器的内存和CPU监控小记

1、  主要使用到的组件有System.Management.dll

2、  主要类为 :ManagementScope

连接远程服务器示例代码:

 private const string PROPERTY_CAPACITY = "Capacity";
private const string PROPERTY_AVAILABLE_BYTES = "AvailableBytes";
private const string PROPERTY_PROCESS_ID = "ProcessId";
private const string PROPERTY_PROCESS_NAME = "Name";
private const string PROPERTY_WORKING_SET_SIZE = "WorkingSetSize"; ConnectionOptions Conn = new ConnectionOptions();
//设定用于WMI连接操作的用户名
Conn.Username = "用户名";
//设定用户的口令
Conn.Password = "密码";
ManagementScope Ms = new ManagementScope("\\\\ip\\root\\cimv2", Conn);
Ms.Connect();

具体查询举例:

 var query1 = new SelectQuery("SELECT * FROM Win32_PhysicalMemory");
var query2 = new SelectQuery("SELECT * FROM Win32_PerfRawData_PerfOS_Memory");
var query3 = new SelectQuery("SELECT * FROM Win32_Processor");
var query4 = new SelectQuery("SELECT * FROM Win32_Process"); var searcher1 = new ManagementObjectSearcher(Ms, query1);
var searcher2 = new ManagementObjectSearcher(Ms, query2);
var searcher3 = new ManagementObjectSearcher(Ms, query3);
var searcher4 = new ManagementObjectSearcher(Ms, query4);

查询内存和CPU:

 var capacity = 0.0;
var free = 0.0;
var cpu = 0.0;
//
foreach (var o in searcher1.Get())
capacity += (double)Convert.ToUInt64(o[PROPERTY_CAPACITY]) / (double)( * );
foreach (var o in searcher2.Get())
free += (double)Convert.ToUInt64(o[PROPERTY_AVAILABLE_BYTES]) / (double)( * );
foreach (var o in searcher3.Get())
{
if (o["LoadPercentage"] != null)
{
cpu = long.Parse(o["LoadPercentage"].ToString());
}
else {
cpu = ;
}
}

举例远程重启某个进程(部分示例代码):

 ConnectionOptions Conn = new ConnectionOptions();
Conn.Username = userName; //设定用户的口令
Conn.Password = pwd;
Ms = new ManagementScope("\\\\" + ip + "\\root\\cimv2", Conn);
Ms.Connect();
ManagementClass processClass = new ManagementClass(Ms, new ManagementPath("Win32_Process"), null);
//获得用来提供参数的对象
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
//设定命令行参数
inParams["CommandLine"] = path;// @"需要启动的进程路径";
//执行程序
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

Other、可以用程序操作批处理文件(.bat)来查询进程或者是关闭进程:

例如查询所有进程 :tasklist /S ip /U 用户名 /P 密码

关闭某个进程:

taskkill  /S ip /U用户名/P 密码  /IM 需要关闭的进程名

部分示例代码:

 public delegate void DelReadStdOutput(string result);
public delegate void DelReadErrOutput(string result);
public event DelReadStdOutput ReadStdOutput;
public event DelReadErrOutput ReadErrOutput;
/// <summary>
/// 注册事件
/// </summary>
private void Init()
{
ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);
ReadErrOutput += new DelReadErrOutput(ReadErrOutputAction); }
//----------------------部分实现代码==================
using (p = new Process())
{ //pause -- 停止
p.StartInfo.FileName = fileName; p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.EnableRaisingEvents = true;
p.Exited += new EventHandler(p_Exited);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived); p.Start();
//读取输出:
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.WaitForExit();
} void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
this.lab_tips.Text = "开始读取数据...读取时间可能有点长,请耐心等待!";
if (e.Data != null)
{
this.Invoke(ReadStdOutput, new object[] { e.Data });
}
}
// 读取进程信息:
public void ReadStdOutputAction(string s)
{ if (num > )
{
budiler.AppendLine(s);
}
this.textBox1.Text = budiler.ToString();
num++;
}

暂时就到这儿了。

上一篇:git 学习笔记 ---标签管理


下一篇:让Git记住用户名和密码