C# 調用 taskkill命令結束服務進程


獲取服務映像名稱

windows服務安裝后會在注冊表中存儲服務信息,路徑是HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[服務名稱]

通過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) > 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;
            }
        }

遠程管理服務需要在本機和遠程機之間建立信任憑據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM