之前给单位做过一个多进程监控的自动关机工具,详见那篇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 }
}

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 - , ) == "txt")
{
if (Regex.IsMatch(duration.Text, "^([0-9]{1,})$"))
{
if (int.Parse(duration.Text) >= )
{
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)*);
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 = ;
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 == )
{
//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();
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相应的命名空间就可以了:

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

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

  1. 用C#写一个多进程监控自动关机工具

    因为据说某server开着就很贵,所以我们跑完测试的job后就要赶紧关机才行,但是测试的job要跑很久,过程中又不需要干什么,所以就得有个守家的,有时候会走很晚.如果有一个自动化关机的工具就好了,当指 ...

  2. 用C#写一个实现进程监控的自动关机工具

    今天QA部门需要进行Performance测试,因为跑job的时间会很长,下班也跑不完.所以想要做一个job运行完毕自动关机的工具. 原理就是检查进程的名称,如果检查不到相应的进程,就说明job已经跑 ...

  3. linux系统监控常用工具

    linux系统监控常用工具 一.系统核心工具包(coreutils) 1./bin/df 报告系统的磁盘空间用量 df -h  显示磁盘分区fdisk -l 2./bin/uname 显示系统信息 u ...

  4. 如何远程关闭一个ASP.NET Core应用?

    在<历数依赖注入的N种玩法>演示系统自动注册服务的实例中,我们会发现输出的列表包含两个特殊的服务,它们的对应的服务接口分别是IApplicationLifetime和IHostingEnv ...

  5. mysql监控管理工具--innotop

    https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/innotop/innotop-1.9. ...

  6. Linux ---> 监控JVM工具

    Linux ---> 监控JVM工具shkingshking 发布时间: 2013/10/10 01:27 阅读: 2642 收藏: 26 点赞: 1 评论: 0 JDK内置工具使用 jps(J ...

  7. Linux系统监控实用工具Glances

    Linux系统监控实用工具Glances Glances安装 Glances安装要求:python >= 2.6 和 psutil >= 0.4.1 1.第一步,安装了python-> ...

  8. python服务端多进程压测工具

    本文描述一个python实现的多进程压测工具,这个压测工具的特点如下: 多进程 在大多数情况下,压测一般适用于IO密集型场景(如访问接口并等待返回),在这种场景下多线程多进程的区分并不明显(详情请参见 ...

  9. 监控小工具(jconsole)

    偶然发现的一个监控小工具 配置好Jmeter运行的环境,在CMD命令中输入:jconsole 即可弹出一个[java监视和管理控制台]

随机推荐

  1. 优化后队列的实现(C语言实现)

    上一篇中的队列的定义与实现(C语言实现) 中.不管是顺序队列还是链式队列,在尾加和删除头部的操作时.总有一个时间复杂度让人不惬意. 比方在顺序队列中,删除头部的操作后,总要将后面全部的结点都向前移动一 ...

  2. DRUPAL 关于 $user 用户权限

    按登录非登录判断: < ?php global $user;/*是否为登录用户*/ if ($user -> uid){/*如果是当前浏览者为登录用户则显示下面的内容*/ print ; ...

  3. iptables阐述防火墙

    一:前言   防火墙,其实说白了讲,就是用于实现Linux下访问控制的功能的,它分为硬件的或者软件的防火墙两种.无论是在哪个网络中,防火墙工作的地方一定是在网络的边缘.而我们的任务就是需要去定义到底防 ...

  4. MassiGra045 简体中文化|打开图片很快

    MassiGra045 简体中文化,是一款对图片的打开预览很高效的工具,据传是日本开发的. 本人之前一直使用,唯一有点缺点就是不能旋转图片. 图片预览 峰回路转: http://pan.baidu.c ...

  5. A. Dreamoon and Stairs(Codeforces Round #272)

    A. Dreamoon and Stairs time limit per test 1 second memory limit per test 256 megabytes input standa ...

  6. 【转】SVN与Git比较

    摘要Svn是目前得到大多数人认可,使用得最多的版本控制管理工具,而Git的优势在于易于本地增加分支和分布式的特性,可离线提交,解决了异地团队协同开发等svn不能解决的问题.本文就这两种版本控制工具的异 ...

  7. 方法$.data()和$.('#test').on()的使用

    1.on() 方法的使用 在选择元素上绑定一个或多个事件的事件处理函数. on()方法绑定事件处理程序到当前选定的jQuery对象中的元素.在jQuery 1.7中,.on()方法 提供绑定事件处理程 ...

  8. 60款与DevOps相关的开源工具

    原文地址:https://elasticbox.com/blog/de ... ools/ 你喜欢免费的东西吗?获得开发者社区支持的自动化,开源的工具是大家梦寐以求的.这里列举了 60+ 款最棒的开源 ...

  9. Apache Storm使用

    Apache Storm 是 Apache 基金会的开源的分布式实时计算系统.与 Hadoop 的批处理相类似,Storm 可以对大量的数据流进行可靠的实时处理,这一过程也称为“流式处理”,是分布式大 ...

  10. SSAS多维数据集以及维度的建立

    首先打开vs建立一个Analysis Services项目,然后点击数据源文件右键[新建数据源],根据数据源向导建立自己的数据源,如图1: 点击[确定],选择刚才的数据连接,点击[下一步]进入模拟信息 ...