zoukankan      html  css  js  c++  java
  • C# 远程服务器 安装、卸载 Windows 服务,读取远程注册表,关闭杀掉远程进程

     
    #region Windows Service 操作 /// /// 安装Windows 服务 /// ///可执行文件的完全路径 public void Install(string webIp, string serviceName, string displayName, string description, string serviceEXEPath) { //检查安装文件是否存在 string remoteFile = PathUtil.GetRemotePath(webIp, serviceEXEPath); if (!File.Exists(remoteFile)) { throw new Exception($"安装文件{serviceEXEPath}在服务器{webIp}上不存在"); } //生成安装指令 string serviceInstallCommand = $"sc \\{webIp} create {serviceName} binpath= "{serviceEXEPath}" displayname= "{displayName}" start= auto "; string updateDescriptionCommand = $"sc \\{webIp} description {serviceName} "{description}" "; string[] cmd = new string[] { serviceInstallCommand, updateDescriptionCommand }; string ss = Cmd(cmd); //检查安装是否成功 string imagePath = GetImagePath(webIp, serviceName); int retryTime = 0; int maxTime = 3; while (retryTime < maxTime && string.IsNullOrEmpty(imagePath)) { Thread.Sleep(1000 * 30); retryTime++; imagePath = GetImagePath(webIp, serviceName); } if (string.IsNullOrEmpty(imagePath)) { throw new Exception($"{serviceName}在{webIp}安装失败,{ss}"); } } /// /// 卸载Windows 服务 /// ///可执行文件的完全路径 public void Uninstall(string webIp, string serviceName, string serviceEXEPath) { //关闭mmc.exe进程,如果windows 服务打开 将无法卸载 var ps = Process.GetProcessesByName(@"mmc", webIp); if (ps.Length > 0) { CloseProcess(webIp, "mmc.exe", string.Empty); } //检查卸载文件是否存在 string remoteFile = PathUtil.GetRemotePath(webIp, serviceEXEPath); if (!File.Exists(remoteFile)) { throw new Exception($"卸载文件{serviceEXEPath}在服务器{webIp}上不存在"); } //生成卸载命令 string[] cmd = new string[] { $"sc \\{webIp} stop {serviceName}", $"sc \\{webIp} delete {serviceName}" }; string ss = Cmd(cmd); string imagePath = GetImagePath(webIp, serviceName); //检查卸载是否成功 int retryTime = 0; int maxTime = 3; while (retryTime < maxTime && !string.IsNullOrEmpty(imagePath)) { Thread.Sleep(1000 * 30); retryTime++; imagePath = GetImagePath(webIp, serviceName); } if (!string.IsNullOrEmpty(imagePath)) { throw new Exception($"{serviceName}在{webIp}卸载失败,{ss}"); } } /// /// 修改windows 服务的显示名称和描述 /// ////////////public void UpdateDisplayNameAndDescription(string webIp, string serviceName, string displayName, string description) { //检查服务是否存在 string imagePath = GetImagePath(webIp, serviceName); if (string.IsNullOrEmpty(imagePath)) { throw new Exception($"服务{serviceName}在{webIp}不存在"); } //生成修改指令 string updateDispalyNameCommand = $"sc \\{webIp} config {serviceName} displayname= "{displayName}""; string updateDescriptionCommand = $"sc \\{webIp} description {serviceName} "{description}" "; string[] cmd = new string[] { updateDispalyNameCommand, updateDescriptionCommand }; string ss = Cmd(cmd); } /// /// sc 停止和启动windows服务 /// /////////public void StopAndStartService(string webIp, string serviceName, bool stop) { string serviceCommand = $"sc \\{webIp} {(stop ? "stop" : "start")} {serviceName}";//停止或启动服务 string[] cmd = new string[] { serviceCommand }; string ss = Cmd(cmd); } /// /// 运行CMD命令 /// ///命令 /// public string Cmd(string[] cmd) { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.StandardInput.AutoFlush = true; for (int i = 0; i < cmd.Length; i++) { p.StandardInput.WriteLine(cmd[i].ToString()); } p.StandardInput.WriteLine("exit"); string strRst = p.StandardOutput.ReadToEnd(); p.WaitForExit(); p.Close(); return strRst; } /// /// 关闭远程计算机进程 /// //////public void CloseProcess(string webIp, string processName, string executablePath) { ConnectionOptions oOptions = new ConnectionOptions(); oOptions.Authentication = AuthenticationLevel.Default; ManagementPath oPath = new ManagementPath($"\\{webIp}\root\cimv2"); ManagementScope oScope = new ManagementScope(oPath, oOptions); ObjectQuery oQuery = new ObjectQuery($"Select * From Win32_Process Where Name = "{processName}""); using (ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oScope, oQuery)) { foreach (ManagementObject oManagementObject in oSearcher.Get()) { if (oManagementObject["Name"].ToString().ToLower() == processName.ToLower()) { /* foreach (PropertyData prop in oManagementObject.Properties) { Console.WriteLine($" {prop.Name} -- - {prop.Value } "); } */ string path = oManagementObject["ExecutablePath"].ToString(); if (string.IsNullOrEmpty(executablePath) || path == executablePath) { oManagementObject.InvokeMethod("Terminate", new object[] { 0 }); } } } } } /// /// 获取远程计算机 服务的执行文件 /// ///远程计算机IP ///远程服务名称 /// public string GetImagePath(string serverIP, string serviceName) { string registryPath = @"SYSTEMCurrentControlSetServices" + serviceName; using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverIP).OpenSubKey(registryPath)) { if (key == null) { return string.Empty; } string value = key.GetValue("ImagePath").ToString(); key.Close(); value = value.Trim('"'); if (value.Contains("SystemRoot")) { return ExpandEnvironmentVariables(serverIP, value); } return value; } } /// /// 替换路径中的SystemRoot /// ///远程计算机IP ///路径 /// private string ExpandEnvironmentVariables(string serverIP, string path) { string systemRootKey = @"SoftwareMicrosoftWindows NTCurrentVersion"; using (RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, serverIP).OpenSubKey(systemRootKey)) { string expandedSystemRoot = key.GetValue("SystemRoot").ToString(); key.Close(); path = path.Replace("%SystemRoot%", expandedSystemRoot); return path; } } /// /// 停止或启动Windows 服务 /// ///服务名称 ///远程IP ///是否是停止 public void StopAndStartWindowsService(string serviceName, string serverIP, bool stop) { using (ServiceController sc = ServiceController.GetServices(serverIP) .FirstOrDefault(x => x.ServiceName == serviceName)) { if (sc == null) { throw new Exception($"{serviceName}不存在于{serverIP}"); } StopAndStartWindowsService(sc, stop); if (stop) { sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 1, 0)); } sc.Close(); } } /// /// 停止或启动Windows 服务 /// //////private void StopAndStartWindowsService(ServiceController sc, bool stop = true) { Action act = () => { ServiceControllerStatus serviceSate = sc.Status; if (stop && (serviceSate == ServiceControllerStatus.StartPending || serviceSate == ServiceControllerStatus.Running)) { //如果当前应用程序池是启动或者正在启动状态,调用停止方法 sc.Stop(); } if (!stop && (serviceSate == ServiceControllerStatus.Stopped || serviceSate == ServiceControllerStatus.StopPending)) { sc.Start(); } }; int retryCount = 0; int maxCount = 4; while (sc != null && retryCount <= maxCount) { try { act(); break; } catch (Exception ex) { if (stop) { string serverIP = sc.MachineName; string serviceName = sc.ServiceName; var imeagePath = GetImagePath(serverIP, serviceName); FileInfo fileInfo = new FileInfo(imeagePath); CloseProcess(serverIP, fileInfo.Name, fileInfo.FullName); } retryCount++; if (retryCount == maxCount) { throw new Exception($"{(stop ? "停止" : "启动")}Windows服务{sc.ServiceName}出错{ex.Message}"); } Thread.Sleep(1000 * 30); } }//end while } /// /// 获取windows 服务状态 /// ///服务名称 ///服务器IP /// public ServiceControllerStatus GetServiceState(string serviceName, string serverIP) { ServiceControllerStatus serviceSate; using (ServiceController sc = ServiceController.GetServices(serverIP) .FirstOrDefault(x => x.ServiceName == serviceName)) { if (sc == null) { throw new Exception($"{serviceName}不存在于{serverIP}"); } serviceSate = sc.Status; sc.Close(); } return serviceSate; } #endregion
    0
     
     
     
     
        C#中,使用ServiceController类控制windows服务,使用之前要先添加引用:System.ServiceProcess,然后在命名空间中引用:using System.ServiceProcess。下面举例获取本机的所有已安装的Windows服务和应用,然后查找某一应用活服务是否已经安装。
    0
     
    代码:
    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Linq;
    7. using System.Text;
    8. using System.Windows.Forms;
    9. using System.ServiceProcess;
    10. namespace 判断机器中是否安装了某项服务或者应用
    11. {
    12. public partial class Form1 : Form
    13. {
    14. public Form1()
    15. {
    16. InitializeComponent();
    17. }
    18. ServiceController[] Services = ServiceController.GetServices();
    19. private bool ExistSth()
    20. {
    21. bool exist = false;
    22. for (int i = 0; i < Services.Length; i++)
    23. {
    24. if (Services[i].DisplayName.ToString() == textBox1.Text.Trim())
    25. exist = true;
    26. }
    27. return exist;
    28. }
    29. private void button1_Click(object sender, EventArgs e)
    30. {
    31. if (ExistSth())
    32. MessageBox.Show("已安装");
    33. else
    34. MessageBox.Show("未安装");
    35. }
    36. private void Form1_Load(object sender, EventArgs e)
    37. {
    38. for (int i = 0; i < Services.Length; i++)
    39. listBox1.Items.Add(Services[i].DisplayName.ToString());
    40. }
    41. }
    42. }
     
           假设某一服务名为ServicesName, 编写开始服务,停止服务,重启服务的代码如下:
    1. private ServiceController _controller;
    2. private void StopService()
    3. {
    4. this._controller = new ServiceController("ServicesName");
    5. this._controller.Stop();
    6. this._controller.WaitForStatus(ServiceControllerStatus.Stopped);
    7. this._controller.Close();
    8. }
    9. private void StartService()
    10. {
    11. this._controller = new ServiceController("ServicesName");
    12. this._controller.Start();
    13. this._controller.WaitForStatus(ServiceControllerStatus.Running);
    14. this._controller.Close();
    15. }
    16. private void ResetService()
    17. {
    18. this._controller = new ServiceController("ServicesName");
    19. this._controller.Stop();
    20. this._controller.WaitForStatus(ServiceControllerStatus.Stopped);
    21. this._controller.Start();
    22. this._controller.WaitForStatus(ServiceControllerStatus.Running);
    23. this._controller.Close();
    24. }
     
     
     
     
  • 相关阅读:
    eclipse用法和技巧
    eclipse常用快捷键集锦
    移动端input的虚拟键盘影响布局
    使用github page + Hexo搭建个人博客折腾记
    javascript数组的排序(sort,冒泡)
    响应式布局与媒体查询
    css属性选择器诸如Class^=,Class*= ,Class$=释义
    怎么预览 GitHub 项目里的网页或 Demo
    常见浏览器的兼容问题(一)
    jQuery常用交互效果
  • 原文地址:https://www.cnblogs.com/devgis/p/14181209.html
Copyright © 2011-2022 走看看