zoukankan      html  css  js  c++  java
  • C# 调用 taskkill命令结束服务进程

    获取服务映像名称

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

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

       //获取服务路径
            private string GetServicePath(string serviceName, string machineName, out string imageName)
            {
                imageName = string.Empty;
                var ret = string.Empty;
    
                string registryPath = @"SYSTEMCurrentControlSetServices" + 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) > 0)
                {
                    var path = serviceFile.Substring(0, serviceFile.IndexOf(".exe") + 4);
                    var fileInfo = new FileInfo(path);
                    imageName = fileInfo.Name;
                    return new FileInfo(path).DirectoryName;
                }
                return ret;
            }

    远程结束进程

    Taskkill命令是   taskkill /s 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(5));
                    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(5));
                    return "正在停止";
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }

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

  • 相关阅读:
    [C/C++] 显示各种C/C++编译器的预定义宏(C11标准、C++11标准、VC、BCB、Intel、GCC)
    [使用心得] 利用按键精灵批量删除pdf中的水印 V2:用于页面内对象数量不定时删除最后一个对象
    [VBScript] allfiles.vbs: 显示子目录下的所有文件的修改时间、大小、全限定名等信息
    [C] wchar_t的格式控制字符(VC、BCB、GCC、C99标准)
    Instructions函数对照表:01 mmintrin.h与MMX指令集
    [C/C++] VC2012编译的程序在WinXP下报告“指定的可执行文件不是有效的 Win32 应用程序”错误
    [C++] cout、wcout无法正常输出中文字符问题的深入调查(2):VC2005的crt源码分析
    [C/C++] ccpuid:CPUID信息模块 V1.02版,支持Mac OS X,支持纯C,增加CPUF常数
    [C] zintrin.h: 智能引入intrinsic函数 V1.01版。改进对Mac OS X的支持,增加INTRIN_WORDSIZE宏
    IDE常用快捷键
  • 原文地址:https://www.cnblogs.com/zeroes/p/csharp-taskkill-service.html
Copyright © 2011-2022 走看看