C# 调用 taskkill命令结束服务进程

时间:2024-07-08 17:06:02

获取服务映像名称

windows服务安装后会在注册表中存储服务信息,路径是HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[服务名称]

C# 调用 taskkill命令结束服务进程

通过ImagePath可以获取到映像名称和服务所在路径,这里的映像名称就是在资源管理器中看到的进程名称,不同于服务名称和显示名称。

   //获取服务路径
private string GetServicePath(string serviceName, string machineName, out string imageName)
{
imageName = string.Empty;
var ret = string.Empty; string registryPath = @"SYSTEM\CurrentControlSet\Services\" + serviceName;
RegistryKey keyHKLM = Registry.LocalMachine; RegistryKey key;
if (string.IsNullOrEmpty(machineName) || machineName == "localhost")
{
key = keyHKLM.OpenSubKey(registryPath); }
else
{
key = RegistryKey.OpenRemoteBaseKey
(RegistryHive.LocalMachine, machineName).OpenSubKey(registryPath);
} string imagePath = key.GetValue("ImagePath").ToString();
key.Close();
var serviceFile = Environment.ExpandEnvironmentVariables(imagePath.Replace("\"", "")); if (serviceFile.IndexOf(".exe", System.StringComparison.CurrentCulture) > )
{
var path = serviceFile.Substring(, serviceFile.IndexOf(".exe") + );
var fileInfo = new FileInfo(path);
imageName = fileInfo.Name;
return new FileInfo(path).DirectoryName;
}
return ret;
}

远程结束进程

Taskkill命令是   taskkill /s C# 调用 taskkill命令结束服务进程172.19.2.107 /f /t /im "[映像名称]" /U [远程机器的用户名] /P [远程机器的密码]

通过C#调用并获取返回值的方法是:

      /// <summary>
/// 结束服务进程
/// </summary>
/// <param name="imagename"></param>
/// <param name="user"></param>
/// <param name="password"></param>
/// <param name="ip"></param>
/// <returns></returns>
private string TaskKillService(string imagename, string user, string password, string ip)
{ var ret = string.Empty;
var process = new Process();
process.StartInfo.FileName = "taskkill.exe";
process.StartInfo.Arguments = string.Format(" /s {0} /f /t /im \"{1}\" /U {2} /P {3}", ip, imagename, user, password);
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
//process.StartInfo.StandardOutputEncoding = Encoding.UTF8; //process.OutputDataReceived += (s, e) =>
//{
// ret += e.Data;
//};
//process.ErrorDataReceived += (s, e) =>
//{
// ret += e.Data;
//};
//process.BeginOutputReadLine();
//process.BeginErrorReadLine();
process.Start(); ret = process.StandardOutput.ReadToEnd();
process.WaitForExit();
process.Close();
return ret;
}

服务管理

通过 System.ServiceProcess.ServiceController 也可以管理服务。

  //获取服务状态
private string GetServiceStatus(string serviceName, string ip)
{
try
{
var service = new System.ServiceProcess.ServiceController(serviceName, ip);
return service.Status.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
} //启动服务
private string StartService(string serviceName, string ip)
{
try
{
var service = new System.ServiceProcess.ServiceController(serviceName, ip);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running)
return "正在运行"; service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds());
return "正在启动";
}
catch (Exception ex)
{
return ex.Message;
}
} //停止服务
private string StopService(string serviceName, string ip)
{
try
{
var service = new System.ServiceProcess.ServiceController(serviceName, ip);
if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped)
return "已经停止";
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds());
return "正在停止";
}
catch (Exception ex)
{
return ex.Message;
}
}

远程管理服务需要在本机和远程机之间建立信任凭据