C# 自动Ping 测试服务器运行状况

通过小程序自动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));
        }

        /// 
        /// 是否能 Ping 通指定的主机
        /// 
        /// ip 地址或主机名或域名
        /// true 通,false 不通
        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();
            }
        }
        /// 

        /// 
        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
    {
        /**//// 
            /// 写入日志文件
            /// 
            /// 
        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();
            }

        }
    }
}

访问数据库的实体类请查看另外一篇随笔。

其实不需要太多代码。主要是偷懒了。都用原来写的现成的东西了。

以后要加油,多写一些东西。慢慢进步。生活需要有动力。

转载于:https://www.cnblogs.com/rongguang/p/5923101.html

你可能感兴趣的:(c#,json,数据库)