Windows IPSEC监控,使用C#编写,输出为一行字符串,可以按照既有IPSEC规则生成模板

  1. using System;
  2. using System.Diagnostics;
  3. using System.IO;
  4. using System.Text;
  5. namespace WindowsIPSecMonitor
  6. {
  7. class WindowsIPSecMonitor
  8. {
  9. //*****颜色提示*****
  10. //红色警告
  11. private static void RedError(string text)
  12. {
  13. Console.ForegroundColor = ConsoleColor.Red;
  14. Console.WriteLine(text);
  15. Console.ForegroundColor = ConsoleColor.White;
  16. }
  17. //黄色提示
  18. private static void YellowWarn(string text)
  19. {
  20. Console.ForegroundColor = ConsoleColor.Yellow;
  21. Console.WriteLine(text);
  22. Console.ForegroundColor = ConsoleColor.White;
  23. }
  24. //绿色提示
  25. private static void GreenPrint(string text)
  26. {
  27. Console.ForegroundColor = ConsoleColor.Green;
  28. Console.WriteLine(text);
  29. Console.ForegroundColor = ConsoleColor.White;
  30. }
  31. //系统命令执行函数
  32. private static string Execute(string command, int seconds)
  33. {
  34. string output = ""; //输出字符串
  35. if (command != null && !command.Equals(""))
  36. {
  37. Process process = new Process();//创建进程对象
  38. ProcessStartInfo startInfo = new ProcessStartInfo();
  39. startInfo.FileName = "cmd.exe";//设定需要执行的命令
  40. startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出
  41. startInfo.UseShellExecute = false;//不使用系统外壳程序启动
  42. startInfo.RedirectStandardInput = false;//不重定向输入
  43. startInfo.RedirectStandardOutput = true; //重定向输出
  44. startInfo.CreateNoWindow = true;//不创建窗口
  45. process.StartInfo = startInfo;
  46. try
  47. {
  48. if (process.Start())//开始进程
  49. {
  50. if (seconds == 0)
  51. {
  52. process.WaitForExit();//这里无限等待进程结束
  53. }
  54. else
  55. {
  56. process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒
  57. }
  58. output = process.StandardOutput.ReadToEnd();//读取进程的输出
  59. }
  60. }
  61. catch
  62. {
  63. }
  64. finally
  65. {
  66. if (process != null)
  67. process.Close();
  68. }
  69. }
  70. return output;
  71. }
  72. //追加写入文件函数
  73. private static void FileRec(string input, string filename)
  74. {
  75. FileStream fs = new FileStream(filename, FileMode.Append);
  76. StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("GB2312"));
  77. //开始写入
  78. sw.Write(input);
  79. //清空缓冲区
  80. sw.Flush();
  81. //关闭流
  82. sw.Close();
  83. fs.Close();
  84. }
  85. //追加一个文件到另一个文件末尾
  86. private static void AppendFile(string Filenamesrc, string Filenamedst)
  87. {
  88. string command = "type " + Filenamesrc + ">>" + Filenamedst;
  89. Execute(command, 1);
  90. }
  91. //生成机器当前操作模板用作比对
  92. private static void GenCurrentLocalTemplates()
  93. {
  94. //命令全局变量
  95. string cmd;
  96. //获取所有的策略名
  97. //cmd = "netsh ipsec static show policy all | findstr \"策略名称\" 2>&1"; //适用中文简体语言环境
  98. cmd = "netsh ipsec static show policy all | findstr \"Policy name\" 2>&1";//适用于英文环境
  99. string[] policy = Execute(cmd, 1).Replace("策略名称", "").Replace("Policy Name", "").Replace("\r\n", "").Replace(":", "").Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
  100. foreach (string policyname in policy)
  101. {
  102. //执行命令生成文件
  103. cmd = "netsh ipsec static show rule all policy = " + policyname + " level = Verbose Format = table>CurrentFullIPSec.log 2>&1";
  104. Execute(cmd, 1);
  105. //处理文件
  106. try
  107. {
  108. //int Counter = 0;
  109. string line;
  110. //处理文件中“是”/“YES”开头不连续的行
  111. StreamReader file1 = new StreamReader("CurrentFullIPSec.log", Encoding.GetEncoding("GB2312"));
  112. while ((line = file1.ReadLine()) != null)
  113. {
  114. //if (line.StartsWith("是"))//适用于中文简体语言环境
  115. if (line.StartsWith("YES"))//适用于英文环境
  116. {
  117. string ProcessedData = Environment.NewLine + line.TrimEnd();
  118. FileRec(ProcessedData, "Temp1.log");
  119. }
  120. else
  121. {
  122. FileRec(line + Environment.NewLine, "Temp1.log");
  123. }
  124. //Counter++;//计数
  125. }
  126. file1.Close();//关闭文件读取流
  127. //截取所有YES开头的行保存到文件
  128. //Counter = 0;
  129. StreamReader file2 = new StreamReader("Temp1.log", Encoding.GetEncoding("GB2312"));
  130. while ((line = file2.ReadLine()) != null)
  131. {
  132. //if (line.StartsWith("是") || line.StartsWith("YES") || line.StartsWith("筛选器列表名称") || line.StartsWith("Rule Name") || line.StartsWith("筛选器操作名称") || line.StartsWith("FilterAction Name") || line.StartsWith("操作") || line.StartsWith("Action") || line.StartsWith("筛选器数目") || line.StartsWith("No. of Filters"))
  133. if (line.StartsWith("是") || line.StartsWith("YES") || line.StartsWith("操作") || line.StartsWith("Action"))
  134. {
  135. string ProcessedData = line.Trim() + Environment.NewLine;
  136. ProcessedData = ProcessedData.Replace(" ", "").Replace("\t", "");
  137. FileRec(ProcessedData, "LocalTemplate.log");
  138. }
  139. //Counter++;//计数
  140. }
  141. file2.Close();//关闭文件读取流
  142. //删除临时文件
  143. File.Delete("Temp1.log");
  144. File.Delete("CurrentFullIPSec.log");
  145. //Counter = 0;
  146. StreamReader file3 = new StreamReader("LocalTemplate.log", Encoding.GetEncoding("GB2312"));
  147. while ((line = file3.ReadLine()) != null)
  148. {
  149. if (line.StartsWith("操作") || line.StartsWith("Action"))
  150. {
  151. //用操作名作为文件名
  152. string NewFilename = line.Trim() + ".txt";
  153. //将文件内容读取进操作名文件
  154. AppendFile("Temp2.log", NewFilename);
  155. File.Delete("Temp2.log");
  156. }
  157. else
  158. {
  159. FileRec(line + Environment.NewLine, "Temp2.log");
  160. }
  161. //Counter++;//计数
  162. }
  163. file3.Close();//关闭文件读取流
  164. File.Delete("LocalTemplate.log");
  165. }
  166. catch (IOException)
  167. {
  168. Console.WriteLine("IO Error! Please consult the programmer!" + Environment.NewLine);
  169. }
  170. }
  171. }
  172. //根据监控模板生成比对文件
  173. private static void GenMonitorTemplates(string TemplateFile)
  174. {
  175. string line;
  176. try
  177. {
  178. StreamReader file = new StreamReader(TemplateFile, Encoding.GetEncoding("GB2312"));
  179. line = file.ReadToEnd();
  180. string[] policylines = line.Split(new string[] { "BLOCK", "PERMIT" }, StringSplitOptions.RemoveEmptyEntries);
  181. FileRec(policylines[0], "MonitorPermitTemplate.txt");
  182. FileRec(policylines[1], "MonitorBlockTemplate.txt");
  183. file.Close();//关闭文件读取流
  184. }
  185. catch (Exception)
  186. {
  187. Console.WriteLine("File IO Error!");
  188. }
  189. }
  190. //比对文件
  191. private static string CompareFile(string FileSRC, string FileDST)
  192. {
  193. //int Counter = 0;
  194. string lineA;
  195. string lineB;
  196. string lineC = "";
  197. if (!File.Exists(FileSRC) || !File.Exists(FileDST))
  198. {
  199. return "Files don't exist! Comparation failed!";
  200. }
  201. else
  202. {
  203. try
  204. {
  205. StreamReader fileA = new StreamReader(FileSRC, Encoding.GetEncoding("GB2312"));
  206. StreamReader fileB = new StreamReader(FileDST, Encoding.GetEncoding("GB2312"));
  207. lineB = fileB.ReadToEnd();
  208. while ((lineA = fileA.ReadLine()) != null)
  209. {
  210. if (!lineB.Contains(lineA.Trim()))
  211. {
  212. lineC += lineA + Environment.NewLine;
  213. }
  214. //Counter++;//计数
  215. }
  216. fileA.Close();//关闭文件读取流
  217. fileB.Close();//关闭文件读取流
  218. }
  219. catch (Exception)
  220. {
  221. Console.WriteLine("File IO error!");
  222. }
  223. return lineC;
  224. }
  225. }
  226. //删除临时文件
  227. private static void DeleteFile()
  228. {
  229. //File.Delete("操作允许.txt");//中文简体环境
  230. //File.Delete("操作阻止.txt");//中文简体环境
  231. File.Delete("ActionPERMIT.txt");//英文环境
  232. File.Delete("ActionBLOCK.txt");//英文环境
  233. File.Delete("MonitorPermitTemplate.txt");//删除根据监控模板生成的PERMIT对比文件
  234. File.Delete("MonitorBlockTemplate.txt");//删除根据监控模板生成的BLOCK对比文件
  235. }
  236. //数据类
  237. public class Data
  238. {
  239. public string time;
  240. public string result;
  241. public string status;
  242. public string JobID;
  243. public void Print_data()
  244. {
  245. Console.WriteLine("{\"result\":\"" + result + "\",\"status\":\"" + status + "\",\"time\":\"" + time + "\",\"id\":\"" + JobID + "\",\"info\":\"\"}");
  246. }
  247. }
  248. //主函数
  249. static void Main(string[] args)
  250. {
  251. string Current_Path = AppDomain.CurrentDomain.BaseDirectory;
  252. //一次赋值使用的全局变量,用于接收命令行字符串
  253. string cmd;
  254. try
  255. {
  256. //*****帮助*****
  257. if (args[0] == "-h" || args[0] == "--help")
  258. {
  259. GreenPrint("Usage:");
  260. GreenPrint("Use WindowsIPSecMonitor.exe --Backup to backup current localmachine's IPSec");
  261. GreenPrint("Use WindowsIPSecMonitor.exe --GCLMT to generate current localmachine's IPSec monitor tempalte");
  262. GreenPrint("Use WindowsIPSecMonitor.exe --Investigate --idle [MonitorTemplateFileName] to see the IPSec comparation result");
  263. GreenPrint("Use WindowsIPSecMonitor.exe [JobID] [Server] [MonitorTemplateFileName] to see the monitor result");
  264. Environment.Exit(0);
  265. }
  266. //备份IPSec
  267. if (args[0] == "--Backup")
  268. {
  269. string time = DateTime.Now.ToString("yyyy-MM-dd#HH.mm.ss");
  270. cmd = "netsh ipsec static exportpolicy file=" + time;
  271. Execute(cmd, 1);
  272. YellowWarn("IPSec has been backed up as " + time + ".ipsec!");
  273. Environment.Exit(0);
  274. }
  275. //生成当前机器用作监控的模板
  276. if (args[0] == "--GCLMT")
  277. {
  278. //生成用作对比的当前机器模板
  279. GenCurrentLocalTemplates();
  280. //cmd = "(echo PERMIT&type 操作允许.txt&echo BLOCK&type 操作阻止.txt)>NewlyGeneratedTempalteForMonitor.txt";//简体中文环境
  281. cmd = "(echo PERMIT&type ActionPERMIT.txt&echo BLOCK&type ActionBLOCK.txt)>NewlyGeneratedTempalteForMonitor.txt";//英文环境
  282. Execute(cmd, 1);
  283. YellowWarn("Template generated! Filename is NewlyGeneratedTempalteForMonitor.txt.");
  284. //File.Delete("操作允许.txt");//简体中文环境
  285. //File.Delete("操作阻止.txt");//简体中文环境
  286. File.Delete("ActionPERMIT.txt");//英文环境
  287. File.Delete("ActionBLOCK.txt");//英文环境
  288. Environment.Exit(0);
  289. }
  290. }
  291. catch (Exception)
  292. {
  293. RedError("Parameter error! Use -h or --help for help");
  294. Environment.Exit(0);
  295. }
  296. //实例化类
  297. Data D = new Data();
  298. D.status = "2";
  299. D.result = "IPSec is fine!";
  300. D.time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  301. try
  302. {
  303. D.JobID = args[0];
  304. }
  305. catch (Exception)
  306. {
  307. RedError("Parameter error! Use -h or --help for help");
  308. Environment.Exit(0);
  309. }
  310. //检查IPSec是否开启
  311. cmd = "netsh ipsec static show policy all";
  312. bool NotAssigned1 = Execute(cmd, 1).Contains("Assigned : NO");
  313. bool NotAssigned2 = Execute(cmd, 1).Contains("已分配 : 否");
  314. if (NotAssigned1 || NotAssigned2)
  315. {
  316. D.status = "4";
  317. D.result = "Policy is not assigned!";
  318. D.Print_data();
  319. Environment.Exit(0);
  320. }
  321. //生成用作对比的当前机器模板
  322. GenCurrentLocalTemplates();
  323. try
  324. {
  325. //处理生成监控模板对比文件,使用命令行参数做文件名
  326. GenMonitorTemplates(Current_Path + args[2]);
  327. //比对文件
  328. //string result1 = CompareFile("MonitorPermitTemplate.txt", "操作允许.txt");//中文简体环境
  329. //string result2 = CompareFile("操作允许.txt", "MonitorPermitTemplate.txt");//中文简体环境
  330. //string result3 = CompareFile("MonitorBlockTemplate.txt", "操作阻止.txt");//中文简体环境
  331. //string result4 = CompareFile("操作阻止.txt", "MonitorBlockTemplate.txt");//中文简体环境
  332. string result1 = CompareFile("MonitorPermitTemplate.txt", "ActionPERMIT.txt");//英文环境
  333. string result2 = CompareFile("ActionPERMIT.txt", "MonitorPermitTemplate.txt");//英文环境
  334. string result3 = CompareFile("MonitorBlockTemplate.txt", "ActionBLOCK.txt");//英文环境
  335. string result4 = CompareFile("ActionBLOCK.txt", "MonitorBlockTemplate.txt");//英文环境
  336. //显示调试信息
  337. if (args[0] == "--Investigate")
  338. {
  339. YellowWarn("LocalPermit lacks the following line(s):");
  340. Console.WriteLine(result1);
  341. YellowWarn("MonitorPermit lacks the fowllowing line(s):");
  342. Console.WriteLine(result2);
  343. YellowWarn("LocalBlock lakcs the following line(s):");
  344. Console.WriteLine(result3);
  345. YellowWarn("MonitorBlock lacks the following line(s):");
  346. Console.WriteLine(result4);
  347. DeleteFile();
  348. }
  349. else
  350. {
  351. if (result1 != "" || result2 != "" || result3 != "" || result4 != "")
  352. {
  353. D.status = "4";
  354. D.result = "IPSec error!";
  355. D.Print_data();
  356. DeleteFile();
  357. Environment.Exit(0);
  358. }
  359. //如果没有错误则输出正确结果
  360. D.Print_data();
  361. DeleteFile();
  362. Environment.Exit(0);
  363. }
  364. }
  365. catch (Exception)
  366. {
  367. RedError("Error! No filename parameter provided!");
  368. DeleteFile();
  369. }
  370. }
  371. }
  372. }

C# Windows IPSEC监控(仅此一家,别无分店)的更多相关文章

  1. paip.windows io监控总结

    paip.windows io监控总结 io的主要参数是个.disk queue length 作者Attilax  艾龙,  EMAIL:1466519819@qq.com 来源:attilax的专 ...

  2. Windows 回调监控 <二>

    在之前的文章Windows 回调监控 <一> 总结了关于CreateProcessNotify,CreateProcessNotifyEx和LoadImageNotify一些用法,之后产生 ...

  3. windows 进程监控 Procmon.exe

    windows 进程监控 Procmon.exe window下一个程序打开太慢,可以用此程序监控.在哪一步慢了,读取文件还是注册表. ProcessMonitor3.2 Process Monito ...

  4. Windows性能计数器监控实践

    Windows性能计数器(Performance Counter)是Windows提供的一种系统功能,它能实时采集.分析系统内的应用程序.服务.驱动程序等的性能数据,以此来分析系统的瓶颈.监控组件的表 ...

  5. python对 windows系统监控插件

    在python编程的windows系统监控中,需要监控监控硬件信息需要两个模块:WMI 和 pypiwin32 .

  6. Windows - 性能监控之磁盘剩余空间大小警报

    开始 -> 运行 -> 键入命令 perfmon.msc 数据收集器(Data Collector Sets) -> 用户自定义(User Defined)

  7. Windows zabbix监控远程进程实现机制

    最近负责zabbix监控部署方面的工作,需要完成本地服务端监控远程虚拟机的运行状态(CPU.打开的进程等),与大家分享下我的实现方法. (1) 首先,需要实现记录zabbix客户端的进程的批处理:za ...

  8. Windows 回调监控 <一>

    在x86的体系结构中,我们常用hook关键的系统调用来达到对系统的监控,但是对于x64的结构,因为有PatchGuard的存在,对于一些系统关键点进行hook是很不稳定的,在很大几率上会导致蓝屏的发生 ...

  9. 探索Windows Azure 监控和自动伸缩系列2 - 获取虚拟机的监控定义和监控数据

    上一篇博文介绍了如何连接Windows Azure: http://www.cnblogs.com/teld/p/5113063.html 本篇我们继续上次的示例代码,获取虚拟机的监控定义和监控数据. ...

随机推荐

  1. PAT 1005 Spell It Right

    1005 Spell It Right (20 分)   Given a non-negative integer N, your task is to compute the sum of all ...

  2. <Closing connections idle longer than 60000 MILLISECONDS> <Closing expired connections>

    日志信息如下: 2017-07-05 18:28:34 -18705 [idle_connection_reaper] DEBUG   - Closing expired connections 20 ...

  3. 《高性能SQL调优精要与案例解析》一书谈主流关系库SQL调优(SQL TUNING或SQL优化)核心机制之——索引(index)

    继<高性能SQL调优精要与案例解析>一书谈SQL调优(SQL TUNING或SQL优化),我们今天就谈谈各主流关系库中,占据SQL调优技术和工作半壁江山的.最重要的核心机制之一——索引(i ...

  4. net core 上传并使用EPPlus导入Excel文件

    1.  cshtml页面 form <form id="form" method="post" action="/SaveValueBatch& ...

  5. 机器学习---笔记----Python基础

    一. python简介 1. python 具有丰富强大的库,常被称为胶水语言,能够把用其他语言制作的各种模块很轻松地联结在一起 2. python强制使用空白符(white space)作为语句缩进 ...

  6. linux磁盘管理 磁盘查看操作

    df查看磁盘分区使用状况 df --显示磁盘分区使用状况 'l' 仅显示本地磁盘(默认) 'a' 显示所有文件系统的磁盘使用情况,包含比如/proc/ 'h' 以1024进制计算最合适的单位显示磁盘容 ...

  7. Win10系列:UWP界面布局进阶8

    StackPanel StackPanel能够以水平或垂直的方式整齐地排列位于其内部的元素.通过设置StackPanel的Orientation属性可以定义内部元素的排列方式,当将Orientatio ...

  8. C# [IPA]IOS In App Purchase(内购)验证(asp.net 版本)

    之前没有做过IOS 内购服务器验证这块,所以找了不少参考资料,网上大多php和java版本,然后自己搞了一个C#版本,希望能给大家一些参考,下面步入正题 在客户端向苹果购买成功之后,我们需要进行二次验 ...

  9. [转载]Java创建WebService服务及客户端实现

    Java创建WebService服务及客户端实现 Java创建WebService服务及客户端实现

  10. sqlalchem表关联(一对多,一对一,多对多)

    简介: 一:一对多关系 1.表示一对多的关系时,在子表类中通过 foreign key (外键)限制本列的值,然后,在父表类中通过 relationship() 方法来引用子表的类. 2.示例代码: ...