通過小程序自動Ping配置文件中的IP地址,間隔時間、IP地址、手機號碼通過配置文件獲得。
廢話不多說,上代碼。
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Windows.Forms; namespace AutoPing { public partial class Form1 : Form { public Form1() { InitializeComponent(); getIps(); LanSearch(); timer1.Interval = interval; timer1.Start(); timer2.Start(); } private void button1_Click(object sender, EventArgs e) { //MessageBox.Show( CmdPing("192.168.1.13")); //displayReply(); //LanSearch(); //MessageBox.Show(new PingServices().GetPingResult("192.168.1.13", 5, 100, 2)); } /// <summary> /// 是否能 Ping 通指定的主機 /// </summary> /// <param name="ip">ip 地址或主機名或域名</param> /// <returns>true 通,false 不通</returns> public bool Ping(string ip) { System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping(); System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions(); options.DontFragment = true; string data = "Test Data!"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 1000; // Timeout 時間,單位:毫秒 System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options); if (reply.Status == System.Net.NetworkInformation.IPStatus.Success) return true; else return false; } private string[] ips = null; private string[] descs = null; private string[] phones = null; private int interval = 20000; private void getIps() { string[] lines = System.IO.File.ReadAllLines("iplist.json"); String ipsFile = ""; foreach (string line in lines) { ipsFile = ipsFile + "\t" + line; } JObject udJson = JObject.Parse(ipsFile); interval = Int32.Parse(udJson["interval"].ToString()); JArray jips = (JArray)JsonConvert.DeserializeObject(udJson["Ips"].ToString()); ips = new string[jips.Count]; descs = new string[jips.Count]; for (int i = 0; i < jips.Count; i++) { //new Loger().WriteLogFile("" + jips[i]["desc"].ToString()); ips[i] = jips[i]["ip"].ToString(); descs[i] = jips[i]["desc"].ToString(); } JArray jphones = (JArray)JsonConvert.DeserializeObject(udJson["phones"].ToString()); phones = new string[jphones.Count]; for (int i = 0; i < jphones.Count; i++) { //new Loger().WriteLogFile("" + jphones[i]["phone"].ToString()); phones[i] = jphones[i]["phone"].ToString(); } } /// <summary> /// </summary> int count = 0; private void LanSearch() { //string ip = "192.168.1.134"; for(int j = 0; j < ips.Length; j++) { if (!Ping(ips[j])) { count++; listBox1.Items.Add(ips[j] + "失敗"+count); Application.DoEvents(); if (count == 5) { listBox1.Items.Add(ips[j] + "失敗超過5次,發送短信"); Application.DoEvents(); new Loger().WriteLogFile(ips[j] + "失敗超過5次,發送短信"); //new Loger().WriteLogFile("insert into sms_messagebase(sms_phone, sms_psnlid, sms_message, sms_createdate, sms_acceptdate, sms_system, sms_type1, sms_type2 , sms_createpsnlid, sms_createcomputer) values('18290815800','PSNL002726','" + ips[j] + "不可達',getdate(),'2000-01-01 00:00:00.000','','','','','') "); for(int xx = 0; xx < phones.Length; xx++) { HisDBHelper.ExcuteSQL("insert into sms_messagebase(sms_phone, sms_psnlid, sms_message, sms_createdate, sms_acceptdate, sms_system, sms_type1, sms_type2 , sms_createpsnlid, sms_createcomputer) values('"+phones[xx]+"','PSNL002726','" +descs[j]+" IP:"+ ips[j] + " 不可達 ',getdate(),'2000-01-01 00:00:00.000','','','','','') "); } ips = remove(ips, j); count = 0; } else { j--; } } else { listBox1.Items.Add(ips[j] + "成功"); Application.DoEvents(); count = 0; } } } private string[] remove(string[] arr,int tx) { List<string> list = arr.ToList(); list.RemoveAt(tx); return list.ToArray(); } private void timer1_Tick(object sender, EventArgs e) { LanSearch(); } private void button1_Click_1(object sender, EventArgs e) { } private void timer2_Tick(object sender, EventArgs e) { DateTime dt = DateTime.Now; //new Loger().WriteLogFile(dt.ToString("yyyy-MM-dd HH:mm:ss") +"" +dt.ToString("yyyy-MM-dd HH:mm:ss").Equals(dt.ToString("yyyy-MM-dd 19:59:00"))); if (dt.ToString("yyyy-MM-dd HH:mm:ss").Equals(dt.ToString("yyyy-MM-dd 09:30:00"))) { getIps(); HisDBHelper.ExcuteSQL("insert into sms_messagebase(sms_phone, sms_psnlid, sms_message, sms_createdate, sms_acceptdate, sms_system, sms_type1, sms_type2 , sms_createpsnlid, sms_createcomputer) values('" + phones[0] + "','PSNL002726','外圍服務檢測程序運行正常',getdate(),'2000-01-01 00:00:00.000','','','','','') "); //new Loger().WriteLogFile("發送"); } } } }
配置文件采用JSON文件,偷懶了,有現成讀取代碼。
{
"interval":"600000",
"Ips": [
{ "ip": "192.168.1.13","desc":"一號機房" },
{ "ip": "192.168.1.222","desc":"二號機房" },
{ "ip": "192.168.1.28","desc":"三號機房" },
{ "ip": "192.168.1.18","desc":"四號機房" }
],
"phones": [
{ "phone": "18888888888" },
{ "phone": "13333333333" }
]
}
讀取JSON需要類庫Newtonsoft.Json.dll,網上自行下載。
寫日志的實體類
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace AutoPing { class Loger { /**//// <summary> /// 寫入日志文件 /// </summary> /// <param name="input"></param> public void WriteLogFile(string input) { /**/ ///指定日志文件的目錄 string fname = Directory.GetCurrentDirectory() + "\\LogFile.txt"; /**/ ///定義文件信息對象 FileInfo finfo = new FileInfo(fname); if (!finfo.Exists) { FileStream fs; fs = File.Create(fname); fs.Close(); finfo = new FileInfo(fname); } /**/ ///判斷文件是否存在以及是否大於2K if (finfo.Length > 1024 * 1024 * 5) { /**/ ///文件超過5MB則重命名 File.Move(Directory.GetCurrentDirectory() + "\\LogFile.txt", Directory.GetCurrentDirectory() + DateTime.Now.TimeOfDay + "\\LogFile.txt"); /**/ ///刪除該文件 //finfo.Delete(); } //finfo.AppendText(); /**/ ///創建只寫文件流 using (FileStream fs = finfo.OpenWrite()) { /**/ ///根據上面創建的文件流創建寫數據流 StreamWriter w = new StreamWriter(fs); /**/ ///設置寫數據流的起始位置為文件流的末尾 w.BaseStream.Seek(0, SeekOrigin.End); /**/ ///寫入“Log Entry : ” w.Write("\n\rLog Entry : "); /**/ ///寫入當前系統時間並換行 w.Write("{0} {1} \n\r", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); /**/ ///寫入日志內容並換行 w.Write(input + "\n\r"); /**/ ///寫入------------------------------------“並換行 w.Write("\n\r------------------------------------\n\r"); /**/ ///清空緩沖區內容,並把緩沖區內容寫入基礎流 w.Flush(); /**/ ///關閉寫數據流 w.Close(); } } } }
訪問數據庫的實體類請查看另外一篇隨筆。
其實不需要太多代碼。主要是偷懶了。都用原來寫的現成的東西了。
以后要加油,多寫一些東西。慢慢進步。生活需要有動力。