工作中,我们有时候需要远程监控服务器的某个服务,而我们又无法登陆服务器,该怎么办?

其实不复杂,只要检测目标端口有没有进程就可以了。当然了,这是要权限的,不过怎么确保安全是另外一个问题了(灵活和安全始终有一点儿矛盾的)。

思路参照实际的工作场景,就是启动一个cmd,然后返回结果用正则表达式找到端口,然后判断服务有没运行。

(本例中平台是win2003 .net c#(Linux平台道理也一样) ,包括检测服务程序,杀死服务和启动服务)


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int chpid = CheckPort("10086");

if (chpid == 0 || chpid == null)
{
StNew();
}
}

public int CheckPort(String Port) ///检查端口有没使用
{
System.Diagnostics.Process pro = new System.Diagnostics.Process();

// 设置命令行、参数
pro.StartInfo.FileName = "cmd.exe";
pro.StartInfo.UseShellExecute = false;
pro.StartInfo.RedirectStandardInput = true;
pro.StartInfo.RedirectStandardOutput = true;
pro.StartInfo.RedirectStandardError = true;
pro.StartInfo.CreateNoWindow = true;
int pid = 0;
// 这里启动CMD
pro.Start();
// 运行命令检查网络情况
pro.StandardInput.WriteLine("netstat -ano");
pro.StandardInput.WriteLine("exit");

// 获取结果
Regex reg = new Regex("\\s+", RegexOptions.Compiled);
string line = null;
while ((line = pro.StandardOutput.ReadLine()) != null)
{
line = line.Trim();
if (line.StartsWith("TCP", StringComparison.OrdinalIgnoreCase))
{
line = reg.Replace(line, ",");

string[] arr = line.Split(',');
if (arr[1].EndsWith(":" + Port))
{
// Response.Write(Port+"端口的进程ID:"+arr[4]+"
");
Label3.Text = Port + "端口的进程ID:" + arr[4] + ",本次监测时间:"+pro.StartTime+"
";
pid = Int32.Parse(arr[4]);
break;
}
}
}

pro.Close();
return pid;
}

public void KillOld(int pid) //
{

System.Diagnostics.Process proold = System.Diagnostics.Process.GetProcessById(pid);
// 处理该进程
try{
proold.Kill();
//Response.Write("该进程已经杀死
");
Label1.Text = "该进程已经杀死
";
}catch(System.ComponentModel.Win32Exception ex){
//Response.Write("该进程不能关闭:
" + ex);
Label1.Text = "该进程不能关闭:
" + ex;
return;
}

}

public void StNew()
{
//声明一个程序信息类
System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
Info.FileName = "D:/……/……XXX.exe";
Info.WorkingDirectory = "D:/……/……XXX.exe";
//声明一个程序类
System.Diagnostics.Process Proc;
try
{
Proc = System.Diagnostics.Process.Start(Info);
}
catch (System.ComponentModel.Win32Exception ex)
{
// Response.Write("系统找不到指定的程序文件
" + ex);
Label2.Text = "系统找不到指定的程序文件
" + ex;
return;
}

//打印出外部程序的开始执行时间
// Response.Write("外部程序的开始执行时间:" + Proc.StartTime);
Label2.Text = "外部程序的开始执行时间:" + Proc.StartTime;

}

protected void Button1_Click(object sender, EventArgs e)
{
int pids = CheckPort("10086");
KillOld(pids);

}
protected void Button2_Click(object sender, EventArgs e)
{
StNew();
}
protected void Button3_Click(object sender, EventArgs e)
{
int pids = CheckPort("10086");
}
}

1.00 平均分 (26%) - 6