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. ACM-选人问题(救济金发放)

    n(n<20)个人站成一圈,逆时针编号为1-n.有两个官员,A从1开始逆时针数,B从n开 始顺时针数.在每一轮中,官员A数k个就停下来,官员B数m个就停下来(注意有可能两个 官员停在同一个人上) ...

  2. 浅谈线程runnable和callable的使用及区别

    线程使用比较广泛,但实际上一般项目很少用上线程,线程常用于优化复杂的程序执行流程,把一些与业务关系关系不大但是必须要执行的流程使用线程的方式让子线程去执行,主流程只返回跟业务有关的信息 runnabl ...

  3. vue中使用transition标签底部导航闪烁问题

    <transition :name="transitionName" :duration="{ enter: 500, leave: 0 }" > ...

  4. java集合的实现细节--ArrayList和LinkedList

     ArrayList和LinkedList的实现差异 List代表一种线性表的数据结构,ArrayList则是一种顺序存储的线性表,ArrayList底层采用动态数组的形式保存每一个集合元素,Link ...

  5. c# 线程的生命周期

    对于线程而言有两种类型:前台线程,后台线程.前台与后台线程性质相同,但终止条件不同. 后台线程:在运行过程中如果宿主进程结束,线程将直接终止执行:在强制终止时,线程即终止执行不论线程代码是否执行完毕. ...

  6. idea中查看java类继承图

    复习java io,看了书里的这张图,太模糊了,想弄个出来放大看,一开始试了idea发现只能看父类,后来折腾了一会试了其他工具才发现还是idea好用. :) 一.打开type hierachy 光标放 ...

  7. mongodb副本集修改配置问题

    因虚拟机地址被占用,需要重新设置ip地址,这时需要修改副本集中的IP地址配置: 1: 查看配置rs.config():需要找到primary主机,在该主节点服务器上才有权限修改配置 2:rs.remo ...

  8. 详谈Oracle12c新特点容器数据库&amp;可插拔数据库(CDB&amp;PDB)

    一般信息 数据字典 CDB_FILE$ DBA_PDBS PDB$SEED CDB_LOCAL_ADMINAUTH$ DBA_PDB_HISTORY PDB_HISTORY$ CDB_PDB_SAVE ...

  9. python操作文件(增、删、改、查)

    内容 global log 127.0.0.1 local2 daemon maxconn 256 log 127.0.0.1 local2 info defaults log global mode ...

  10. excel 单元格0 不显示的最佳方法

    excel单元格设自定义格式, 条件:可以单元格内容判断后再设置格式.条件格式化只限于使用三个条件,其中两个条件是明确的,另个是“所有的其他”.条件要放到方括号中.必须进行简单的比较.例如这个条件:单 ...