首页 > 代码库 > C# 自动Ping 测试服务器运行状况

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));        }        /// <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 = http://www.mamicode.com/"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();            }        }    }}

访问数据库的实体类

using System;using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.SqlClient;using System.Reflection;/// <summary>///     数据库助手///     @浅时光///     #240815752/// </summary>namespace Checkup{    public class ZDBHelper    {        //连接字符串        static string strConn = ConfigurationManager.ConnectionStrings["sqlString"].ToString();        #region 执行查询,返回DataTable对象-----------------------        public static DataTable GetTable(string strSQL)        {            return GetTable(strSQL, null);        }        public static DataTable GetTable(string strSQL, SqlParameter[] pas)        {            return GetTable(strSQL, pas, CommandType.Text);        }        /// <summary>        /// 执行查询,返回DataTable对象        /// </summary>        /// <param name="strSQL">sql语句</param>        /// <param name="pas">参数数组</param>        /// <param name="cmdtype">Command类型</param>        /// <returns>DataTable对象</returns>        public static DataTable GetTable(string strSQL, SqlParameter[] pas, CommandType cmdtype)        {            Console.ForegroundColor = ConsoleColor.Red;            Console.WriteLine("GetTable:" + strSQL);            DataTable dt = new DataTable(); ;            try            {                using (SqlConnection conn = new SqlConnection(strConn))                {                    SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);                    da.SelectCommand.CommandType = cmdtype;                    if (pas != null)                    {                        da.SelectCommand.Parameters.AddRange(pas);                    }                    da.Fill(dt);                }            }            catch (Exception ee)            {                Console.WriteLine(">" + ee.Message);            }            return dt;        }        #endregion        #region 执行查询,返回DataSet对象-------------------------        public static DataSet GetDataSet(string strSQL)        {            return GetDataSet(strSQL, null);        }        public static DataSet GetDataSet(string strSQL, SqlParameter[] pas)        {            return GetDataSet(strSQL, pas, CommandType.Text);        }        /// <summary>        /// 执行查询,返回DataSet对象        /// </summary>        /// <param name="strSQL">sql语句</param>        /// <param name="pas">参数数组</param>        /// <param name="cmdtype">Command类型</param>        /// <returns>DataSet对象</returns>        public static DataSet GetDataSet(string strSQL, SqlParameter[] pas, CommandType cmdtype)        {            DataSet dt = new DataSet(); ;            using (SqlConnection conn = new SqlConnection(strConn))            {                SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);                da.SelectCommand.CommandType = cmdtype;                if (pas != null)                {                    da.SelectCommand.Parameters.AddRange(pas);                }                da.Fill(dt);            }            return dt;        }        #endregion        #region 执行查询,返回List<T>对象-------------------------        /// <summary>        ///         /// </summary>        /// <typeparam name="T">转换类型</typeparam>        /// <param name="strSQL">sql</param>        /// <param name="tableIndex">需要转换表的索引</param>        /// <returns></returns>        public static T GetObject<T>(string strSQL)        {            Console.WriteLine("GetObject:" + strSQL);            SqlDataReader sdr = GetReader(strSQL);            try            {                if (sdr.Read())                {                    //创建泛型对象                    T _t = Activator.CreateInstance<T>();                    //获取对象所有属性                    PropertyInfo[] propertyInfo = _t.GetType().GetProperties();                    for (int j = 0; j < sdr.FieldCount; j++)                    {                        foreach (PropertyInfo info in propertyInfo)                        {                            //属性名称和列名相同时赋值                            if (sdr.GetName(j).ToUpper().Equals(info.Name.ToUpper()))                            {                                if (sdr[j] != DBNull.Value)                                {                                    info.SetValue(_t, sdr[j], null);                                }                                else                                {                                    info.SetValue(_t, null, null);                                }                                break;                            }                        }                    }                    return _t;                }                else {                    return default(T);                }            }            catch (Exception ee)            {                Console.WriteLine("<>" + ee.Message);            }            return default(T);        }        /// <summary>        /// DataSetToList List        /// </summary>        /// <typeparam name="T">转换类型</typeparam>        /// <param name="strSQL">sql</param>        /// <param name="tableIndex">需要转换表的索引</param>        /// <returns></returns>        public static IList<T> GetList<T>(string strSQL, int tableIndex)        {            Console.WriteLine("GetList:" + strSQL);            DataSet dataSet = GetDataSet(strSQL, null);            //确认参数有效            if (dataSet == null || dataSet.Tables.Count <= 0 || tableIndex < 0)                return null;            DataTable dt = dataSet.Tables[tableIndex];            IList<T> list = new List<T>();            for (int i = 0; i < dt.Rows.Count; i++)            {                //创建泛型对象                T _t = Activator.CreateInstance<T>();                //获取对象所有属性                PropertyInfo[] propertyInfo = _t.GetType().GetProperties();                for (int j = 0; j < dt.Columns.Count; j++)                {                    foreach (PropertyInfo info in propertyInfo)                    {                        //属性名称和列名相同时赋值                        if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))                        {                            if (dt.Rows[i][j] != DBNull.Value)                            {                                info.SetValue(_t, dt.Rows[i][j], null);                            }                            else                            {                                info.SetValue(_t, null, null);                            }                            break;                        }                    }                }                list.Add(_t);            }            return list;        }        #endregion        #region 执行非查询存储过程和SQL语句-----------------------------        public static int ExcuteProc(string ProcName)        {            return ExcuteSQL(ProcName, null, CommandType.StoredProcedure);        }        public static int ExcuteProc(string ProcName, SqlParameter[] pars)        {            return ExcuteSQL(ProcName, pars, CommandType.StoredProcedure);        }        public static int ExcuteSQL(string strSQL)        {            return ExcuteSQL(strSQL, null);        }        public static int ExcuteSQL(string strSQL, SqlParameter[] paras)        {            return ExcuteSQL(strSQL, paras, CommandType.Text);        }        /// 执行非查询存储过程和SQL语句        /// 增、删、改        /// </summary>        /// <param name="strSQL">要执行的SQL语句</param>        /// <param name="paras">参数列表,没有参数填入null</param>        /// <param name="cmdType">Command类型</param>        /// <returns>返回影响行数</returns>        public static int ExcuteSQL(string strSQL, SqlParameter[] paras, CommandType cmdType)        {            Console.ForegroundColor = ConsoleColor.Red;            Console.WriteLine("ExcuteSQL:" + strSQL);            int i = 0;            using (SqlConnection conn = new SqlConnection(strConn))            {                SqlCommand cmd = new SqlCommand(strSQL, conn);                cmd.CommandType = cmdType;                if (paras != null)                {                    cmd.Parameters.AddRange(paras);                }                conn.Open();                i = cmd.ExecuteNonQuery();                conn.Close();            }            return i;        }        #endregion        #region 执行查询返回第一行,第一列---------------------------------        public static int ExcuteScalarSQL(string strSQL)        {            return ExcuteScalarSQL(strSQL, null);        }        public static int ExcuteScalarSQL(string strSQL, SqlParameter[] paras)        {            return ExcuteScalarSQL(strSQL, paras, CommandType.Text);        }        public static int ExcuteScalarProc(string strSQL, SqlParameter[] paras)        {            return ExcuteScalarSQL(strSQL, paras, CommandType.StoredProcedure);        }        /// <summary>        /// 执行SQL语句,返回第一行,第一列        /// </summary>        /// <param name="strSQL">要执行的SQL语句</param>        /// <param name="paras">参数列表,没有参数填入null</param>        /// <returns>返回影响行数</returns>        public static int ExcuteScalarSQL(string strSQL, SqlParameter[] paras, CommandType cmdType)        {            Console.WriteLine("ExcuteScalarSQL:" + strSQL);            int i = 0;            using (SqlConnection conn = new SqlConnection(strConn))            {                SqlCommand cmd = new SqlCommand(strSQL, conn);                cmd.CommandType = cmdType;                if (paras != null)                {                    cmd.Parameters.AddRange(paras);                }                conn.Open();                i = Convert.ToInt32(cmd.ExecuteScalar());                conn.Close();            }            return i;        }        #endregion        #region 查询获取单个值------------------------------------        /// <summary>        /// 调用不带参数的存储过程获取单个值        /// </summary>        /// <param name="ProcName"></param>        /// <returns></returns>        public static object GetObjectByProc(string ProcName)        {            return GetObjectByProc(ProcName, null);        }        /// <summary>        /// 调用带参数的存储过程获取单个值        /// </summary>        /// <param name="ProcName"></param>        /// <param name="paras"></param>        /// <returns></returns>        public static object GetObjectByProc(string ProcName, SqlParameter[] paras)        {            return GetObject(ProcName, paras, CommandType.StoredProcedure);        }        /// <summary>        /// 根据sql语句获取单个值        /// </summary>        /// <param name="strSQL"></param>        /// <returns></returns>        public static object GetObject(string strSQL)        {            return GetObject(strSQL, null);        }        /// <summary>        /// 根据sql语句 和 参数数组获取单个值        /// </summary>        /// <param name="strSQL"></param>        /// <param name="paras"></param>        /// <returns></returns>        public static object GetObject(string strSQL, SqlParameter[] paras)        {            return GetObject(strSQL, paras, CommandType.Text);        }        /// <summary>        /// 执行SQL语句,返回首行首列        /// </summary>        /// <param name="strSQL">要执行的SQL语句</param>        /// <param name="paras">参数列表,没有参数填入null</param>        /// <returns>返回的首行首列</returns>        public static object GetObject(string strSQL, SqlParameter[] paras, CommandType cmdtype)        {            Console.ForegroundColor = ConsoleColor.Red;            Console.WriteLine("GetObject:" + strSQL);            object o = null;            using (SqlConnection conn = new SqlConnection(strConn))            {                SqlCommand cmd = new SqlCommand(strSQL, conn);                cmd.CommandType = cmdtype;                if (paras != null)                {                    cmd.Parameters.AddRange(paras);                }                conn.Open();                o = cmd.ExecuteScalar();                conn.Close();            }            return o;        }        #endregion        #region 查询获取DataReader------------------------------------        /// <summary>        /// 调用不带参数的存储过程,返回DataReader对象        /// </summary>        /// <param name="procName">存储过程名称</param>        /// <returns>DataReader对象</returns>        public static SqlDataReader GetReaderByProc(string procName)        {            return GetReaderByProc(procName, null);        }        /// <summary>        /// 调用带有参数的存储过程,返回DataReader对象        /// </summary>        /// <param name="procName">存储过程名</param>        /// <param name="paras">参数数组</param>        /// <returns>DataReader对象</returns>        public static SqlDataReader GetReaderByProc(string procName, SqlParameter[] paras)        {            return GetReader(procName, paras, CommandType.StoredProcedure);        }        /// <summary>        /// 根据sql语句返回DataReader对象        /// </summary>        /// <param name="strSQL">sql语句</param>        /// <returns>DataReader对象</returns>        public static SqlDataReader GetReader(string strSQL)        {            return GetReader(strSQL, null);        }        /// <summary>        /// 根据sql语句和参数返回DataReader对象        /// </summary>        /// <param name="strSQL">sql语句</param>        /// <param name="paras">参数数组</param>        /// <returns>DataReader对象</returns>        public static SqlDataReader GetReader(string strSQL, SqlParameter[] paras)        {            return GetReader(strSQL, paras, CommandType.Text);        }        /// <summary>        /// 查询SQL语句获取DataReader        /// </summary>        /// <param name="strSQL">查询的SQL语句</param>        /// <param name="paras">参数列表,没有参数填入null</param>        /// <returns>查询到的DataReader(关闭该对象的时候,自动关闭连接)</returns>        public static SqlDataReader GetReader(string strSQL, SqlParameter[] paras, CommandType cmdtype)        {            Console.WriteLine("GetReader:" + strSQL);            SqlDataReader sqldr = null;            SqlConnection conn = new SqlConnection(strConn);            SqlCommand cmd = new SqlCommand(strSQL, conn);            cmd.CommandType = cmdtype;            if (paras != null)            {                cmd.Parameters.AddRange(paras);            }            conn.Open();            //CommandBehavior.CloseConnection的作用是如果关联的DataReader对象关闭,则连接自动关闭            sqldr = cmd.ExecuteReader(CommandBehavior.CloseConnection);            return sqldr;        }        public static string Inf()        {            SqlConnection conn = new SqlConnection(strConn);            SqlCommand MyCommand = new SqlCommand("USERAUTH", conn);            //MyCommand.CommandType = CommandType.StoredProcedure;            //MyCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));            //MyCommand.Parameters["@id"].Value = http://www.mamicode.com/3;>//MyCommand.Parameters.Add(new SqlParameter("@inpass", SqlDbType.NVarChar));            //MyCommand.Parameters["@inpass"].Value = "http://www.mamicode.com/3";            MyCommand.Parameters.AddWithValue("@id", 3);  //给输入参数赋值            MyCommand.Parameters.AddWithValue("@inpass", "3");  //给输入参数赋值            MyCommand.Parameters.Add(new SqlParameter("@ret", SqlDbType.NVarChar));            MyCommand.Parameters["@ret"].Direction = ParameterDirection.ReturnValue;            conn.Open();            MyCommand.ExecuteNonQuery();            Console.WriteLine(MyCommand.Parameters["@ret"].Value.ToString());            return "succ";        }        //存储过程        public static object ExcuteNonQuery_Proc_Output(string procName, SqlParameter[] parameters, string outName)        {            SqlConnection conn = new SqlConnection(strConn);            SqlCommand cmd = new SqlCommand();            cmd.Connection = conn;            cmd.CommandType = CommandType.StoredProcedure;            cmd.CommandText = procName;            for (int i = 0; i < parameters.Length; i++)            {                Console.WriteLine(i + ">" + parameters[i].ToString());                cmd.Parameters.Add(parameters[i]);            }            conn.Open();            int n = cmd.ExecuteNonQuery();            object o = cmd.Parameters[outName].Value;            conn.Close();            Console.WriteLine("完成");            return o;        }        #endregion        #region 批量插入数据---------------------------------------------        /// <summary>        /// 往数据库中批量插入数据        /// </summary>        /// <param name="sourceDt">数据源表</param>        /// <param name="targetTable">服务器上目标表</param>        public static void BulkToDB(DataTable sourceDt, string targetTable)        {            SqlConnection conn = new SqlConnection(strConn);            SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);   //用其它源的数据有效批量加载sql server表中            bulkCopy.DestinationTableName = targetTable;    //服务器上目标表的名称            bulkCopy.BatchSize = sourceDt.Rows.Count;   //每一批次中的行数            try            {                conn.Open();                if (sourceDt != null && sourceDt.Rows.Count != 0)                    bulkCopy.WriteToServer(sourceDt);   //将提供的数据源中的所有行复制到目标表中            }            catch (Exception ex)            {                throw ex;            }            finally            {                conn.Close();                if (bulkCopy != null)                    bulkCopy.Close();            }        }        #endregion    }}

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

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

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