使用WMI读取远程主机的日志信息
发布时间:2020-12-14 00:56:21 所属栏目:Linux 来源:网络整理
导读:需求: 需要读取远程主机信息,实时获取服务信息(检测所有远程服务器是否有报错,如果有报错,发送错误具体信息到指定邮件) //构建IP实体类 namespace MonitorCaveatService{ public class IPEntity { /// summary /// 监控目标的ServerName /// /summary st
需求: 需要读取远程主机信息,实时获取服务信息(检测所有远程服务器是否有报错,如果有报错,发送错误具体信息到指定邮件) //构建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 = ""; ? 发送邮件功能类 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_Site_Name,Device_Type,Statistic_Name,Statistic_Value,entity.SourceName,entity.Category,entity.EventCode,AtTime(entity.TimeWritten,1),2),entity.User,entity.Message.Contains(" If additional information is available,it can be found at") ? entity.Message:entity.Message+ "nr"+" 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 + "rrrrr" + "发件时间:" + DateTime.Now); } catch (Exception ex) { _log.FatalFormat("邮件发送失败:"+"rrr"+ ex.Message + "rrrr" + 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="[email?protected]" /> <!--抄送,号分割,支持个人、组--> <add key="CC_email" value="[email?protected]" /> <!--配置多个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
pause
Uninstall %SystemRoot%Microsoft.NETFrameworkv4.0.30319installutil.exe /u MonitorCaveatService.exe ? ? ? 创建WinService(在VS2017中叫安装程序) //此处需要注意,Account需要选择LocalSystem
??? public partial class WinService : ServiceBase
??? { ??????? 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") ??????????????? {
??????????????????? using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:logOnStart.txt",true))
??????????????????? { ??????????????????????? sw.WriteLine("进入:OnShutdown方法" + DateTime.Now); ??????????????????? }
??????????????????? item.Kill();
??????????????????? 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(); ??????????????? } ??????????? }
??????? } ??? }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |