需求:
需要读取远程主机信息,实时获取服务信息(检测所有远程服务器是否有报错,如果有报错,发送错误具体信息到指定邮件)
//构建IP实体类
namespace MonitorCaveatService { public class IPEntity { /// <summary> /// 监控目标的ServerName /// </summary> string strServerName = string.Empty; public string ServerName { get { return strServerName; } set { strServerName = value; } } /// <summary> /// 监控目标的IP地址 /// </summary> string strMonitorIP = string.Empty; public string MonitorIP { get { return strMonitorIP; } set { strMonitorIP = value; } } /// <summary> /// 监控目标的Key /// </summary> string strServerkey = string.Empty; public string Serverkey { get { return strServerkey; } set { strServerkey = value; } } /// <summary> /// 监控目标的用户名 /// </summary> string strMonitorUserID = string.Empty; public string MonitorUserID { get { return strMonitorUserID; } set { strMonitorUserID = value; } } /// <summary> /// 监控目标的密码 /// </summary> string strMonitorPassword = string.Empty; public string MonitorPassword { get { return strMonitorPassword; } set { strMonitorPassword = value; } } string strMonitorDeviceID = string.Empty; /// <summary> /// 监控目标的ID /// </summary> public string MonitorDeviceID { get { return strMonitorDeviceID; } set { strMonitorDeviceID = value; } } } }
构建日志实体类
public class EventLogEntity { string strEventType = string.Empty; /// <summary> /// 日志类型 /// </summary> public string EventType { get { return strEventType; } set { strEventType = value; } } public DateTime TimeWritten { get { if (strTimeWritten.ToString("yyyy-MM-dd") == "0001-01-01"||strTimeWritten.ToString()==""||strTimeWritten.ToString()==null) return DateTime.Now; else return strTimeWritten; } set { strTimeWritten = value; } } private DateTime strTimeWritten; string strCategory = string.Empty; /// <summary> /// 日志种类 /// </summary> public string Category { get { return strCategory; } set { strCategory = value; } } string strSourceName = string.Empty; /// <summary> /// 日志来源 /// </summary> public string SourceName { get { return strSourceName; } set { strSourceName = value; } } /// <summary> /// Eevnet ID /// </summary> string strEventIdentifier = string.Empty; public string EventIdentifier { get { return strEventIdentifier; } set { strEventIdentifier = value; } } string strRecordNumber = string.Empty; /// <summary> /// 行号 /// </summary> public string RecordNumber { get { return strRecordNumber; } set { strRecordNumber = value; } } string strEventCode = string.Empty; /// <summary> /// 日志编码 /// </summary> public string EventCode { get { return strEventCode; } set { strEventCode = value; } } string strCategoryString = string.Empty; /// <summary> /// CategoryString /// </summary> public string CategoryString { get { return strCategoryString; } set { strCategoryString = value; } } string strMessage = string.Empty; /// <summary> /// 详细错误 /// </summary> public string Message { get { return strMessage; } set { strMessage = value; } } string strComputerName = string.Empty; /// <summary> /// 电脑名称 /// </summary> public string ComputerName { get { return strComputerName; } set { strComputerName = value; } } string strUser = string.Empty; /// <summary> /// 用户 /// </summary> public string User { get { return strUser; } set { strUser= value; } } string strType = string.Empty; public string Type { get { return strType; } set { strType = value; } } string strData = string.Empty; public string Data { get { return strData; } set { strData = value; } } string strInsertionStrings = string.Empty; public string InsertionStrings { get { return strInsertionStrings; } set { strInsertionStrings = value; } } string strLogfile = string.Empty; public string Logfile { get { return strLogfile; } set { strLogfile = value; } } string strTimeGenerated = string.Empty; public string TimeGenerated { get { return strTimeGenerated; } set { strTimeGenerated = value; } } #region 扩展Device类 string strDevice_ID = string.Empty; public string Device_ID { get { return strDevice_ID; } set { strDevice_ID = value; } } string strDevice_IP_Address = string.Empty; public string Device_IP_Address { get { return strDevice_IP_Address; } set { strDevice_IP_Address = value; } } string strDevice_Name = string.Empty; public string Device_Name { get { return strDevice_Name; } set { strDevice_Name = value; } } string strDevice_Nick_Name = string.Empty; public string Device_Nick_Name { get { return strDevice_Nick_Name; } set { strDevice_Nick_Name = value; } } string strDevice_Site_Name = string.Empty; public string Device_Site_Name { get { return strDevice_Site_Name; } set { strDevice_Site_Name = value; } } string strStatistic_Name = string.Empty; public string Statistic_Name { get { return strStatistic_Name; } set { strStatistic_Name = value; } } #endregion }
//获取服务器信息
using MonitorCaveatService; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Management; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; namespace WindowsCaveatService { public class EventLogService { private readonly object _lock = new object(); private Boolean isLocal = false; private string scopePath = "";
private log4net.ILog _log = log4net.LogManager.GetLogger("WMIService"); string tempTime = string.Empty;
#region 使用WMI读取远程主机的日志信息时以下几点需要注意: //1.检查服务器DCOM 键值是否为Y: //HKEY_LOCAL_MACHINE→SOFTWARE→Microsoft→Ole→EnableDCOM的值 //2.检查登陆用户是否具有权限: //运行DCOMCNFG--Componet Service--Computers-My Computer--右键Properties--COM Secuntiy-- Launch and Activation... //Edit Limits---ADD User---ALLOW 勾选所有权限 //3.关闭防火墙 //4.local访问rootcimv2 在dos 命令行里执行: wbemtest.exe,执行成功之后,在工具里设置地址如: \10.186.32.128 ootcimv2 //5.检查 local和root的WMI Service是否都有启动,检查方法:services.msc找到WMI并查看状态 #endregion private string GetEventTypeString(string EventType) { switch (EventType) { case "1": return "Error"; case "2": return "Warning"; case "3": return "Information"; case "4": return "Security Audit Success"; case "5": return "Security Audit Failure"; } return null; } private string GetEventTypeInt(string EventType) { switch (EventType) { case "Error": return "1"; case "Warning": return "2"; case "Information": return "3"; case "Security Audit Success": return "4"; case "Security Audit Failure": return "5"; } return null; } Dictionary<string, string> dict = new Dictionary<string, string>(); public void GetEventLogService() { System.Management.ObjectQuery oq; System.Management.ConnectionOptions co = new ConnectionOptions(); string tempYZM = string.Empty; // string eventCode = "14500"; string MonitorPassword = string.Empty;//连接需要的密码 string MonitorUserID = string.Empty;//连接需要的用户名 string MonitorDeviceID = string.Empty; string serverName = string.Empty; string MonitorIP = string.Empty; List<IPEntity> ipd = new List<IPEntity>(); ipd = GetName();//获取所有的服务器信息 string eventCodes = GetValue("EventCodes"); while (true) { for (int i = 0; i < ipd.Count; i++) { if (!dict.ContainsKey(ipd[i].ServerName)) { dict.Add(ipd[i].ServerName, DateTime.Now.AddSeconds(-20).ToString("yyyy /MM/dd HH:mm:ss")); } MonitorIP = ipd[i].MonitorIP.ToString(); //监测的目标机器IP地址 MonitorUserID = ipd[i].MonitorUserID.ToString();//监测目标的UserID MonitorPassword = ipd[i].MonitorPassword.ToString();//监测目标的Passsword MonitorDeviceID = ipd[i].MonitorDeviceID.ToString(); co.Username = MonitorUserID; co.Password = MonitorPassword; Boolean tempYZ = RemoteConnectValidate(MonitorIP, MonitorUserID, MonitorPassword); //Ntevt.dll if (tempYZ == true) { //可以访问服务器 _log.FatalFormat("已经成功链接服务器:"+"IP地址:" + MonitorIP + " " + "时间:" + DateTime.Now); } else { //无法访问服务器 _log.FatalFormat("链接服务器失败:"+"IP地址:" + MonitorIP + " " + "时间:" + DateTime.Now); } _log.FatalFormat("线程睡开始时间:" + DateTime.Now); bool EmStatus = GetEventLogList(MonitorIP, MonitorDeviceID, co, eventCodes, ipd[i].ServerName); Thread.Sleep(9000); _log.FatalFormat("线程睡结束时间:" + DateTime.Now); } } } // 验证是否能连接到远程计算机 public bool RemoteConnectValidate(string host, string userName, string password) { ConnectionOptions connectionOptions = new ConnectionOptions(); connectionOptions.Username = userName; connectionOptions.Password = password; ManagementScope managementScope = new ManagementScope("\\" + host + "\root\cimv2", connectionOptions); try { managementScope.Connect(); } catch (Exception ex) { //ex.Message.ToString(); _log.FatalFormat("验证链接远程主机:(" + "RemoteConnectValidate出现异常):"+" "+ ex.Message + " " + DateTime.Now); } return managementScope.IsConnected; } #region//获取日志文件 /// <summary> /// 获取日志文件 /// </summary> /// <param name="topNumber">多少条</param> /// <param name="eventCode">事件ID</param> /// <param name="startTime">开始时间</param> /// <param name="endTime">结束时间</param> /// <returns>返回集合</returns> public bool GetEventLogList(string machineName, string MonitorDeviceID, System.Management.ConnectionOptions co, string eventCodes, string serverName) { List<EventLogEntity> logList = new List<EventLogEntity>(); string ErrorLevel = GetValue("ErrorLevel"); EmailToBMW em = new EmailToBMW(); string startTime; string endTime; //根据键值对的形式取出所属服务器的时间 //原因:多个服务器的时间可能不一致 startTime = dict[serverName]; endTime = Convert.ToDateTime(startTime).AddSeconds(20).ToString("yyyy /MM/dd HH:mm:ss"); System.Management.ManagementScope ms = new System.Management.ManagementScope("\\" + machineName + "\root\cimv2", co); try { //条件语句 StringBuilder query = new StringBuilder(); StringBuilder strWhere = new StringBuilder(); query.Append(@"select EventType, TimeWritten, Category, SourceName, EventIdentifier, RecordNumber,CategoryString,EventCode,Message,ComputerName, User,Type,Data,InsertionStrings,Logfile,TimeGenerated from Win32_NTLogEvent "); //日志ID //eventCodes需要特殊处理 //原因:WQL查询语句使用IN('','')时无法支持多个 if (!string.IsNullOrEmpty(eventCodes)) { var tempSQL = string.Empty; eventCodes.Split(',').ToList().ForEach( t => tempSQL += " or eventCode ='" + t + "'" ); if (!string.IsNullOrEmpty(tempSQL)) tempSQL = " AND (" + tempSQL.Remove(0, 4) + " )"; strWhere.Append(tempSQL); } //错误级别 GetEventTypeInt if (!string.IsNullOrEmpty(ErrorLevel)) { strWhere.Append(" AND EventType='"); strWhere.Append(GetEventTypeInt(ErrorLevel)); strWhere.Append("'"); } // 开始日期 if (!string.IsNullOrEmpty(startTime)) { strWhere.Append(" AND TimeWritten >='"); strWhere.Append(getDmtfFromDateTime(startTime)); strWhere.Append("'"); } //结束日期 if (!string.IsNullOrEmpty(endTime)) { strWhere.Append(" AND TimeWritten <'"); strWhere.Append(getDmtfFromDateTime(endTime)); strWhere.Append("'"); } string laststrWhere = strWhere.ToString(); //如果有检索条件 if (!string.IsNullOrEmpty(laststrWhere)) { laststrWhere = " where " + laststrWhere.Substring(4); } //组合条件 query.Append(laststrWhere); //值 ManagementObjectCollection moCollection = null; //如果是本地 if (isLocal) { ManagementScope scope = new ManagementScope(scopePath); scope.Connect(); ObjectQuery objectQuery = new ObjectQuery(query.ToString()); //WQL语句,设定的WMI查询内容和WMI的操作范围,检索WMI对象集合 ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, objectQuery); //异步调用WMI查询 moCollection = Searcher.Get(); } //表示远程 else { //设定通过WMI要查询的内容 ObjectQuery Query = new ObjectQuery(query.ToString()); //WQL语句,设定的WMI查询内容和WMI的操作范围,检索WMI对象集合 ManagementObjectSearcher Searcher = new ManagementObjectSearcher(ms, Query); //异步调用WMI查询 moCollection = Searcher.Get(); } //循环 if (moCollection != null) { foreach (ManagementObject mObject in moCollection) { EventLogEntity eventLog = new EventLogEntity(); //日志类型 eventLog.EventType = mObject["EventType"] == null ? string.Empty : GetEventTypeString(mObject["EventType"].ToString()); //日志种类 eventLog.Category = mObject["Category"] == null ? string.Empty : mObject["Category"].ToString(); //日志种类 eventLog.CategoryString = mObject["CategoryString"] == null ? string.Empty : mObject["CategoryString"].ToString(); //日志编码 eventLog.EventCode = mObject["EventCode"] == null ? string.Empty : mObject["EventCode"].ToString(); //日志ID eventLog.EventIdentifier = mObject["EventIdentifier"] == null ? string.Empty : mObject["EventIdentifier"].ToString(); //行号 eventLog.RecordNumber = mObject["RecordNumber"] == null ? string.Empty : mObject["RecordNumber"].ToString(); //日期 eventLog.TimeWritten = mObject["TimeWritten"] == null ? DateTime.Now : ConverSpecialOfDate((mObject["TimeWritten"].ToString())); //日志来源 eventLog.SourceName = mObject["SourceName"] == null ? string.Empty : mObject["SourceName"].ToString(); //详细错误 eventLog.Message = mObject["Message"] == null ? string.Empty : mObject["Message"].ToString(); //电脑名称 eventLog.ComputerName = mObject["ComputerName"] == null ? string.Empty : mObject["ComputerName"].ToString(); //用户 eventLog.User = mObject["User"] == null ? "N/A" : mObject["User"].ToString(); //类型 eventLog.Type = mObject["Type"] == null ? string.Empty : mObject["Type"].ToString(); eventLog.Data = mObject["Data"] == null ? string.Empty : mObject["Data"].ToString(); eventLog.InsertionStrings = mObject["InsertionStrings"] == null ? string.Empty : mObject["InsertionStrings"].ToString(); eventLog.Type = mObject["TimeGenerated"] == null ? string.Empty : mObject["TimeGenerated"].ToString(); eventLog.Device_ID = MonitorDeviceID; eventLog.Device_IP_Address = machineName; eventLog.Device_Site_Name = "BMW SF Production CIC I-Monitor"; logList.Add(eventLog); } // logList查询出来的数据是按倒序排列 //这个时间作为下次开始的时间 tempTime = logList.Count == 0 ? endTime : logList[0].TimeWritten.ToString("yyyy /MM/dd HH:mm:ss"); dict[serverName] = tempTime; _log.FatalFormat("获取日志结束时间:" + tempTime); em.senMail(logList); } } catch (Exception ex) { //throw ex; _log.FatalFormat("WMI获取日志GetEventLogList出错"+ ex.Message, "时间:" + DateTime.Now); return false; } // return true; } #endregion #region//根据行号检索错误信息 /// <summary> /// 根据行号检索错误信息 /// </summary> /// <param name="recordNumber">行号</param> /// <returns>返回错误信息</returns> public string GetErrMsg(uint recordNumber) { string Msg = string.Empty; try { //条件语句 StringBuilder query = new StringBuilder(); query.Append("select Message, InsertionStrings from Win32_NTLogEvent where "); query.Append(" RecordNumber='"); query.Append(recordNumber); query.Append("'"); //值 ManagementObjectCollection moCollection = null; //如果是本地 if (isLocal) { ManagementScope scope = new ManagementScope(scopePath); scope.Connect(); ObjectQuery objectQuery = new ObjectQuery(query.ToString()); //WQL语句,设定的WMI查询内容和WMI的操作范围,检索WMI对象集合 ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, objectQuery); //异步调用WMI查询 moCollection = Searcher.Get(); } //表示远程 else { //设定通过WMI要查询的内容 ObjectQuery Query = new ObjectQuery(query.ToString()); //WQL语句,设定的WMI查询内容和WMI的操作范围,检索WMI对象集合 // ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Ms, Query); ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Query); //异步调用WMI查询 moCollection = Searcher.Get(); } //检索错误信息 foreach (ManagementObject mObject in moCollection) { //错误信息 string message = mObject["Message"] == null ? string.Empty : mObject["Message"].ToString(); //错误信息 string[] insertionStrings = mObject["InsertionStrings"] == null ? null : (string[])mObject["InsertionStrings"]; //如果有错误信息 if (string.IsNullOrEmpty(message)) { if (insertionStrings.Length > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < insertionStrings.Length; i++) { sb.Append(insertionStrings[i]); sb.Append(" "); } Msg = sb.ToString(); } } else { Msg = message; } } } catch { } //return return string.IsNullOrEmpty(Msg) ? "无错误信息,请与管理员联系核对!" : Msg; } #endregion /// <summary> /// 去读Config配置里的信息 /// </summary> /// <returns></returns> public string GetValue(string appKey) { XmlDocument xDoc = new XmlDocument(); xDoc.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MonitorCaveatService.config")); XmlNode xNode; XmlElement xElem; xNode = xDoc.SelectSingleNode("//appSettings"); xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']"); if (xElem != null) return xElem.GetAttribute("value"); else return ""; } /// <summary> /// 根据节点名字循环读取 /// </summary> /// <returns></returns> public List<IPEntity> GetName() { List<IPEntity> listIP = new List<IPEntity>(); try { XmlNode node = GetIPCaveat(); XmlNodeList nodes = node.SelectNodes("add"); if (nodes != null) { foreach (XmlNode node1 in nodes) { IPEntity ipy = new IPEntity(); ipy.Serverkey = node1.Attributes["Serverkey"].Value; ipy.MonitorIP = node1.Attributes["MonitorIP"].Value; ipy.ServerName = node1.Attributes["ServerName"].Value; ipy.MonitorUserID = node1.Attributes["MonitorUserID"].Value; ipy.MonitorPassword = node1.Attributes["MonitorPassword"].Value; ipy.MonitorDeviceID = node1.Attributes["MonitorDeviceID"].Value; listIP.Add(ipy); } } } catch (Exception ex) { _log.FatalFormat("解析XMLGetName方法出错:"+ex.Message); } return listIP; } /// <summary> /// 获取到IPCaveat节点的信息 /// </summary> /// <returns></returns> public XmlNode GetIPCaveat() { XmlDocument xDoc = new XmlDocument(); xDoc.Load(Path.Combine( AppDomain.CurrentDomain.BaseDirectory,"MonitorCaveatService.config")); return xDoc.SelectSingleNode("//appSettings//IPCaveat"); } #region 将输入的字符串转化为日期。如果字符串的格式非法,则返回当前日期 /// <summary> /// Author:JohnTang /// </summary> /// <param name="strInput">输入字符串</param> /// <returns>日期对象</returns> public static DateTime ConvertStringToDate(string strInput) { DateTime oDateTime; try { oDateTime = DateTime.Parse(strInput); } catch (Exception) { oDateTime = DateTime.Today; } return oDateTime; } #endregion #region 特殊字符串转换成年/月/日 时:分:秒 public DateTime ConverSpecialOfDate(string _date) { DateTime dt=DateTime.Now; try { string str = _date.Substring(0, _date.IndexOf(".")); string str1 = str.Substring(0, 4);//年 string str2 = str.Substring(4, 2);//月 string str3 = str.Substring(6, 2);//日 string str4 = str.Substring(8, 2);//时 string str5 = str.Substring(10, 2);//分 string str6 = str.Substring(12, 2);//秒 string temps = str1 + "/" + str2 + "/" + str3 + " " + str4 + ":" + str5 + ":" + str6; dt = DateTime.Parse(temps); } catch (Exception ex) { _log.FatalFormat("在转换时间方法ConverSpecialOfDate时出错:"+ex.Message+"参数:"+_date); } return dt; } #endregion private static string getDmtfFromDateTime(DateTime dateTime) { return ManagementDateTimeConverter.ToDmtfDateTime(dateTime); } private static string getDmtfFromDateTime(string dateTime) { DateTime dateTimeValue = Convert.ToDateTime(dateTime); return getDmtfFromDateTime(dateTimeValue); } private static string getDateTimeFromDmtfDate(string dateTime) { return ManagementDateTimeConverter.ToDateTime(dateTime).ToString(); } }
}
发送邮件功能类
namespace MonitorCaveatService { public class EmailToBMW { private log4net.ILog _log = log4net.LogManager.GetLogger("EmailService"); /// <summary> /// 邮件发送前的准备工作,遍历List调用发送发放 /// </summary> /// <param name="tempEntity"></param> /// <returns></returns> public bool senMail(List<EventLogEntity> tempEntity) { bool SendResult = false; List<EventLogEntity> entity = new List<EventLogEntity>(); foreach (EventLogEntity item in tempEntity) { item.Category = tempEntity[0].Category; item.CategoryString = tempEntity[0].CategoryString; item.ComputerName = tempEntity[0].ComputerName; item.Data = tempEntity[0].Data; item.Device_ID = tempEntity[0].Device_ID; item.Device_IP_Address = tempEntity[0].Device_IP_Address; item.Device_Name = tempEntity[0].Device_Name; item.Device_Nick_Name = tempEntity[0].Device_Nick_Name; item.Device_Site_Name = tempEntity[0].Device_Site_Name; item.EventCode = tempEntity[0].EventCode; item.EventIdentifier = tempEntity[0].EventIdentifier; item.EventType = tempEntity[0].EventType; item.InsertionStrings = tempEntity[0].InsertionStrings; item.Logfile = tempEntity[0].Logfile; item.Message = tempEntity[0].Message; item.RecordNumber = tempEntity[0].RecordNumber; item.SourceName = tempEntity[0].SourceName; item.Statistic_Name = tempEntity[0].Statistic_Name; item.TimeGenerated = tempEntity[0].TimeGenerated; item.TimeWritten = tempEntity[0].TimeWritten; item.Type = tempEntity[0].Type; item.User = tempEntity[0].User; SendResult = sendingMail(item); } if (SendResult == false) { return false; } else { return true; } } public bool sendingMail(EventLogEntity entity) { //给定发件箱的信息,这里需要写死,是指邮件的地址以及账号密码 string smtpService = "xxx";//IP地址 string sendEmail = @"xxx"; string sendEmail_BM = "xxx"; string sendpwd = "xxx"; EventLogService TempEmails = new EventLogService(); string ToEmail = TempEmails.GetValue("TO_email");//获取收件人邮箱地址 string CCEmalil = TempEmails.GetValue("CC_email");//获取抄送人邮箱地址 string Body1 = entity.EventCode; string Body2 = entity.InsertionStrings; //确定smtp服务器地址 实例化一个Smtp客户端 SmtpClient smtpclient = new SmtpClient(); smtpclient.Host = smtpService; smtpclient.Port = 25; ///以下字段为测试字段,需要通过查询进行填充 #region 以下字段为测试字段,需要通过查询进行填充 string Device_Type = "GenericWindowsServer"; string Statistic_Name = "EventMessage"; string Statistic_Value = "Error"; #endregion //确定发件地址 MailAddress sendAddress = new MailAddress(sendEmail_BM); //构造一个Email的Message对象 内容信息 MailMessage mailMessage = new MailMessage(); //确定发送人地址 mailMessage.From = sendAddress; MailAddress mailAddress = null; ToEmail.Split(',').ToList().ForEach( t => { if (!string.IsNullOrEmpty(t)) { mailAddress = new MailAddress(t); mailMessage.To.Add(mailAddress); } } ); CCEmalil.Split(',').ToList().ForEach( t => { if (!string.IsNullOrEmpty(t)) { mailAddress = new MailAddress(t); mailMessage.CC.Add(t); } } ); mailMessage.Subject = entity.EventType+" Message From Production CIC I-Monitor"+entity.ComputerName;//邮件发送主题 mailMessage.SubjectEncoding = System.Text.Encoding.UTF8; //建立邮件内容发送模板 StringBuilder str = new StringBuilder(); str.AppendFormat(@" Server: {0} IP: {1} {2} Message : Device ID={3} Device IP Address={4} Device Name={5} Device Nick Name={6} Device Site Name={7} Device Type={8} Statistic Name={9} Statistic Value=Event Type: {10} Event Source: {11} Event Category: {12} Event ID: {13} Date: {14} Time: {15} User: {16} Computer: {17} Description: {18} TimeStamp={19} ", entity.ComputerName, entity.Device_IP_Address, entity.EventType, entity.Device_ID, entity.Device_IP_Address, entity.ComputerName, entity.ComputerName, entity.Device_Site_Name, Device_Type, Statistic_Name , Statistic_Value, entity.SourceName, entity.Category, entity.EventCode, AtTime(entity.TimeWritten, 1), AtTime(entity.TimeWritten, 2), entity.User, entity.ComputerName , entity.Message.Contains(" If additional information is available, it can be found at") ? entity.Message:entity.Message+ " "+" If additional information is available, it can be found at https://xxx.aspx?EventID="+entity.EventCode+"", entity.TimeWritten.AddHours(8) ); mailMessage.Body = str.ToString(); mailMessage.BodyEncoding = System.Text.Encoding.UTF8; //如果服务器支持安全连接,则将安全连接设为true smtpclient.EnableSsl = false; try { //是否使用默认凭据,若为false,则使用自定义的证书,就是下面的networkCredential实例对象 smtpclient.UseDefaultCredentials = false; //指定邮箱账号和密码,用户凭据 NetworkCredential networkCredential = new NetworkCredential(sendEmail, sendpwd); smtpclient.Credentials = networkCredential; //发送邮件 smtpclient.Send(mailMessage); // Console.WriteLine("发送邮件成功"); _log.FatalFormat("发送邮件成功:"+"发件人:" + sendEmail + " " + "发件时间:" + DateTime.Now); } catch (Exception ex) { _log.FatalFormat("邮件发送失败:"+" "+ ex.Message + " " + DateTime.Now); } return true; } /// <summary> /// 输出时间处理 /// </summary> /// <param name="TempDatetime"></param> /// <param name="tempInput"></param> /// <returns></returns> public static string AtTime(DateTime TempDatetime, int tempInput) { string tempTime = string.Empty; DateTime dt = TempDatetime; var _date = "20/11/2018"; var str = _date.Split('/'); //n // dt = Convert.ToDateTime(string.Format("{0}-{1}-{2} 00:00:00", str[2],str[1],str[0])); string TempTime = string.Empty; //表示截取日/月/年的格式 if (tempInput == 1) { TempTime = dt.ToString("dd/MM/yyyy"); } //表示截取如:12:00的格式 else if (tempInput == 2) { TempTime = dt.ToString("hh:mm"); } //表示截取如:日/月/年 时:分:秒 else if (tempInput == 3) { TempTime = dt.ToString("dd/MM/yyyy HH:MM:SS"); } return TempTime; } } }
Config配置
<?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <!--Error级别--> <add key="ErrorLevel" value="Error" /> <!--监控服务:每新增一个机器,则需要添加一个新的子节点--> <IPCaveat description="IP"> <add Serverkey="Server1" MonitorIP="xxx" ServerName="xxx" MonitorUserID="xxx" MonitorPassword="xxx" MonitorDeviceID="101" /> </IPCaveat> <!--收件人,多人用英文,号分割,支持个人、组--> <add key="TO_email" value="xxx@xxx.com" /> <!--抄送,多人用英文,号分割,支持个人、组--> <add key="CC_email" value="xxx@xxx.com" /> <!--配置多个EventCode多个用英文逗号分割,--> <add key="EventCodes" value="14500,1561" /> </appSettings> </configuration>
安装卸载程序(.bat文件)
Install
%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe MonitorCaveatService.exe
Net Start WinService
sc config ServiceTest start= auto
Net Start WinService
sc config ServiceTest start= auto
pause
Uninstall
%SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe /u MonitorCaveatService.exe
pause
创建WinService(在VS2017中叫安装程序)
//此处需要注意,Account需要选择LocalSystem
public partial class WinService : ServiceBase
{
public WinService()
{
InitializeComponent();
}
{
public WinService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\logOnStart.txt", true))
{
sw.WriteLine("进入:OnStart方法" + DateTime.Now);
}
EventLogService el = new EventLogService();
el.GetEventLogService();
}
protected override void OnShutdown()
{
var arr = Process.GetProcesses();
foreach (var item in arr)
{
if (item.ProcessName == "MonitorCaveatService")
{
{
var arr = Process.GetProcesses();
foreach (var item in arr)
{
if (item.ProcessName == "MonitorCaveatService")
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\logOnStart.txt", true))
{
sw.WriteLine("进入:OnShutdown方法" + DateTime.Now);
}
{
sw.WriteLine("进入:OnShutdown方法" + DateTime.Now);
}
item.Kill();
item.Close();
}
}
}
item.Close();
}
}
}
protected override void OnStop()
{
var arr = Process.GetProcesses();
foreach (var item in arr)
{
if (item.ProcessName == "MonitorCaveatService")
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\logOnStart.txt", true))
{
sw.WriteLine("进入:OnStop方法" + DateTime.Now);
}
item.Kill();
item.Close();
}
}
{
var arr = Process.GetProcesses();
foreach (var item in arr)
{
if (item.ProcessName == "MonitorCaveatService")
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\logOnStart.txt", true))
{
sw.WriteLine("进入:OnStop方法" + DateTime.Now);
}
item.Kill();
item.Close();
}
}
}
}
}