多进程监控自动关机工具升级远程关闭多台server——C# works with PowerShell

简介: 之前给单位做过一个多进程监控的自动关机工具,详见那篇blog。 这次领导又加了需求,说要等进程监控结束后,不止需要关闭主控端server,还需要关闭其他servers。于是就用到了我上篇文章所介绍的知识——通过PowerShell来远程管理计算机。

之前给单位做过一个多进程监控的自动关机工具,详见那篇blog

这次领导又加了需求,说要等进程监控结束后,不止需要关闭主控端server,还需要关闭其他servers。于是就用到了我上篇文章所介绍的知识——通过PowerShell来远程管理计算机。

由于PowerShell和C#都是基于.NET的,所以也不需要胶水把这两种语言粘合到一起。可以充分的利用两者各自的优点,结合到一起!(PowerShell在远程管理server这方面是很擅长的。)

于是我修改了之前的工具UI界面,多出了两个textbox,分别用来选择server配置文件(需要关闭的除主控端的server的相关信息都记录在该配置文件中)和PowerShell脚本文件(主要负责远程方面的操作):

server配置文件格式如下,一行对应一台server,每一行中的server ip、用户名、密码用空格隔开:

选用的PowerShell脚本文件代码如下:

function ShutDownRemoteComputers
{
    param($ip,$user,$pwd)
    #winrm s winrm/config/client '@{TrustedHosts=10.1.23.60"}'
    $sen = "'@{TrustedHosts=`""+$ip+"`"}'"
    winrm s winrm/config/client $sen
    $pw = convertto-securestring -AsPlainText -Force -String $pwd
    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pw
    $session = New-PSSession $ip -Credential $cred
    icm $session {shutdown -s -t 0}
}

Winform程序在主控端结束进程检查后,会先关闭server配置文件中的servers,然后关闭主控端server(本机)。

代码如下(粉色部分为新加的和远程相关的主要内容):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Runspaces;

namespace AutoShutDown2
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void chooseFileButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileName = new OpenFileDialog();
            fileName.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
            if (fileName.ShowDialog() == DialogResult.OK)
            {
                filePath.Text = fileName.FileName;
            }
        }

        private void filePath_Click(object sender, EventArgs e)
        {
            filePath.Text = "";
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            if (filePath.Text.ToString().Substring(filePath.Text.Length - 3, 3) == "txt")
            {
                if (Regex.IsMatch(duration.Text, "^([0-9]{1,})$"))
                {
                    if (int.Parse(duration.Text) >= 30)
                    {
                        if (serverFilePath.Text == "")
                        {
                            MessageBox.Show("You should choose a server configuration file first.");
                        }
                        else
                        {
                            MessageBox.Show("PCAS will check with a duration of " + duration.Text + "s.");
                            this.Hide();
                            //Check the processes with the duration.
                            DurationStart();
                        }
                    }
                    else 
                    {
                        MessageBox.Show("The integer number should be greater than 30 seconds.");
                    }
                }
                else
                {
                    MessageBox.Show("You can only type in an integer for duration.");
                    duration.Text = "";
                }
            }
            else 
            {
                MessageBox.Show("You can only choose a txt to be a configuration file.");
                filePath.Text = "";
            }
        }

        private void DurationStart()
        {
            //Check the process's status with the duration.
            System.Timers.Timer tmr = new System.Timers.Timer(int.Parse(duration.Text)*1000);
            tmr.Elapsed += new System.Timers.ElapsedEventHandler(CheckProcess);
            tmr.AutoReset = true;
            tmr.Enabled = true;
        }

        private void CheckProcess(object source, System.Timers.ElapsedEventArgs e)
        {
            //Check the processes's status in the config file.
            using (FileStream fs = new FileStream(filePath.Text, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs))
                {
                    string line;
                    int numOfTheProcesses = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        var processes = System.Diagnostics.Process.GetProcesses();
                        foreach (var process in processes)
                        {
                            if (process.ProcessName == line)
                            {
                                //Find the objective process.
                                //MessageBox.Show(line);
                                numOfTheProcesses++;
                            }
                        }
                    }
                    if (numOfTheProcesses == 0)
                    {
                        //No such process, shut down the computer.
                        //MessageBox.Show("The computer is ready to be shut down.");
                        //Shut down the computer
                        ShutDown();
                    }
                    sr.Close();
                }
                fs.Close();
            }
        }

        private void ShutDown()
        {
            //Shut down the other computers.
            ShutDownOthers(serverFilePath.Text, scriptPathText.Text);
            //Shut down this computer.
            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
            myProcess.StartInfo.FileName = "cmd.exe";
            myProcess.StartInfo.UseShellExecute = false;
            myProcess.StartInfo.RedirectStandardInput = true;
            myProcess.StartInfo.RedirectStandardOutput = true;
            myProcess.StartInfo.RedirectStandardError = true;
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.Start();
            Thread.Sleep(3000);
            myProcess.StandardInput.WriteLine("shutdown -s -t 0"); 
            //MessageBox.Show("Shut down self.");
        }

        private void ShutDownOthers(string serverFilePath,string scriptPath)
        {
            //Read servers from the server file and shut down the servers.
            //Read the servers.
            string filePath = serverFilePath;
            using (FileStream fs1 = new FileStream(filePath, FileMode.Open))
            {
                try
                {
                    using (StreamReader sr1 = new StreamReader(fs1))
                    {
                        string line;
                        try
                        {
                            while ((line = sr1.ReadLine()) != null)
                            {
                                var elements = line.Split();
                                string ip = elements[0].ToString();
                                string user = elements[1].ToString();
                                string pwd = elements[2].ToString();
                                //Shut down the server checked from the line.
                                //Open the PowerShell.
                                using (Runspace runspace = RunspaceFactory.CreateRunspace())
                                {
                                    //MessageBox.Show("Run PowerShell.");
                                    string script = File.ReadAllText(scriptPath);
                                    runspace.Open();
                                    PowerShell ps = PowerShell.Create();
                                    ps.Runspace = runspace;
                                    ps.AddScript(script);
                                    ps.Invoke();
                                    ps.AddCommand("ShutDownRemoteComputers").AddParameter("ip", ip).AddParameter("user", user).AddParameter("pwd", pwd);
                                    ps.Invoke();
                                    //MessageBox.Show("Shut down others");
                                }
                            }
                        }
                        finally
                        {
                            sr1.Close();
                        }
                    }
                }
                finally
                {
                    fs1.Close();
                }
            }       
        }

        private void chooseServerFileButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileName = new OpenFileDialog();
            fileName.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
            if (fileName.ShowDialog() == DialogResult.OK)
            {
                serverFilePath.Text = fileName.FileName;
            }
        }

        private void serverFilePath_Click(object sender, EventArgs e)
        {
            serverFilePath.Text = "";
        }

        private void scriptPathText_Click(object sender, EventArgs e)
        {
            scriptPathText.Text = "";
        }

        private void chooseScriptButton_Click(object sender, EventArgs e)
        {
            OpenFileDialog fileName = new OpenFileDialog();
            fileName.Filter = "文本文件|*.*|C#文件|*.cs|所有文件|*.*";
            if (fileName.ShowDialog() == DialogResult.OK)
            {
                scriptPathText.Text = fileName.FileName;
            }
        }
    }
}

至于远程所需要在主控端和被控端所做的准备工作,一语概括就是在主控端和被控端都Enable-PSRemoting(全选A),然后互相配置Winrm信任就ok了(这两步都是在PowerShell中进行的,详见通过PowerShell来远程管理计算机这篇blog)。

//Open the PowerShell.
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
     //MessageBox.Show("Run PowerShell.");
     string script = File.ReadAllText(scriptPath);
     runspace.Open();
     PowerShell ps = PowerShell.Create();
     ps.Runspace = runspace;
     ps.AddScript(script);
     ps.Invoke();
     ps.AddCommand("ShutDownRemoteComputers")
        .AddParameter("ip", ip)
        .AddParameter("user", user)
        .AddParameter("pwd", pwd);
     ps.Invoke();
}

上面这段代码就是在C#中调用PowerShell脚本的关键。想要在C#中引用PowerShell需要事先add reference:

找到这个reference最快捷的方式就是在PowerShell中输入[psobject].Assembly.Location

然后在代码里using相应的命名空间就可以了:

亲测通过后获得了相关部门领导赠送的可爱多一个。

相关文章
|
2月前
|
存储 监控 算法
员工电脑监控系统中的 C# 链表算法剖析-如何监控员工的电脑
当代企业管理体系中,员工电脑监控已成为一个具有重要研究价值与实践意义的关键议题。随着数字化办公模式的广泛普及,企业亟需确保员工对公司资源的合理利用,维护网络安全环境,并提升整体工作效率。有效的电脑监控手段对于企业实现这些目标具有不可忽视的作用,而这一过程离不开精妙的数据结构与算法作为技术支撑。本文旨在深入探究链表(Linked List)这一经典数据结构在员工电脑监控场景中的具体应用,并通过 C# 编程语言给出详尽的代码实现与解析。
53 5
|
11月前
|
监控 Linux 应用服务中间件
探索Linux中的`ps`命令:进程监控与分析的利器
探索Linux中的`ps`命令:进程监控与分析的利器
200 13
|
5月前
|
存储 监控 算法
企业内网监控系统中基于哈希表的 C# 算法解析
在企业内网监控系统中,哈希表作为一种高效的数据结构,能够快速处理大量网络连接和用户操作记录,确保网络安全与效率。通过C#代码示例展示了如何使用哈希表存储和管理用户的登录时间、访问IP及操作行为等信息,实现快速的查找、插入和删除操作。哈希表的应用显著提升了系统的实时性和准确性,尽管存在哈希冲突等问题,但通过合理设计哈希函数和冲突解决策略,可以确保系统稳定运行,为企业提供有力的安全保障。
|
6月前
|
缓存 C# 开发者
C# 一分钟浅谈:Blazor Server 端开发
本文介绍了 Blazor Server,一种基于 .NET 的 Web 开发模型,允许使用 C# 和 Razor 语法构建交互式 Web 应用。文章从基础概念、创建应用、常见问题及解决方案、易错点及避免方法等方面详细讲解,帮助开发者快速上手并提高开发效率。
151 2
|
6月前
|
开发框架 缓存 .NET
C# 一分钟浅谈:Blazor Server 端开发
Blazor Server 是基于 ASP.NET Core 的框架,允许使用 C# 和 Razor 语法构建交互式 Web 应用。本文介绍 Blazor Server 的基本概念、快速入门、常见问题及解决方案,帮助开发者快速上手。涵盖创建应用、基本组件、数据绑定、状态管理、跨组件通信、错误处理和性能优化等内容。
310 1
|
12月前
|
缓存 监控 调度
第六十一章 使用 ^PERFSAMPLE 监控进程 - 分析维度
第六十一章 使用 ^PERFSAMPLE 监控进程 - 分析维度
87 0
|
8月前
|
监控
MASM32写的免费软件“ProcView/系统进程监控” V1.4.4003 说明和下载
MASM32写的免费软件“ProcView/系统进程监控” V1.4.4003 说明和下载
|
8月前
|
监控 Ubuntu API
Python脚本监控Ubuntu系统进程内存的实现方式
通过这种方法,我们可以很容易地监控Ubuntu系统中进程的内存使用情况,对于性能分析和资源管理具有很大的帮助。这只是 `psutil`库功能的冰山一角,`psutil`还能够提供更多关于系统和进程的详细信息,强烈推荐进一步探索这个强大的库。
102 1
|
9月前
|
数据采集 监控 API
如何监控一个程序的运行情况,然后视情况将进程杀死并重启
这篇文章介绍了如何使用Python的psutil和subprocess库监控程序运行情况,并在程序异常时自动重启,包括多进程通信和使用日志文件进行断点重续的方法。
|
9月前
|
监控 安全 C#
使用C#如何监控选定文件夹中文件的变动情况?
使用C#如何监控选定文件夹中文件的变动情况?
156 19

相关实验场景

更多
下一篇
oss创建bucket