需求:
需要讀取遠程主機信息,實時獲取服務信息(檢測所有遠程服務器是否有報錯,如果有報錯,發送錯誤具體信息到指定郵件)
//構建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訪問root\cimv2 在dos 命令行里執行: wbemtest.exe,執行成功之后,在工具里設置地址如: \\10.186.32.128\root\cimv2 //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 + "\r" + "時間:" + DateTime.Now); } else { //無法訪問服務器 _log.FatalFormat("鏈接服務器失敗:"+"IP地址:" + MonitorIP + "\r" + "時間:" + 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出現異常):"+"\r\r\r"+ ex.Message + "\r\r\r" + 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+ "\n\r"+" 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 + "\r\r\r\r\r" + "發件時間:" + DateTime.Now); } catch (Exception ex) { _log.FatalFormat("郵件發送失敗:"+"\r\r\r"+ ex.Message + "\r\r\r\r" + 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.NET\Framework\v4.0.30319\installutil.exe MonitorCaveatService.exe
Net Start WinService
sc config ServiceTest start= auto
Net Start WinService
sc config ServiceTest start= auto
pause
Uninstall
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.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();
}
}
}
}
}