通过小程序自动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 = ; // 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 = ;
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 = ; 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 = ; i < jphones.Count; i++)
{
//new Loger().WriteLogFile("" + jphones[i]["phone"].ToString());
phones[i] = jphones[i]["phone"].ToString();
}
}
/// <summary> /// </summary>
int count = ;
private void LanSearch()
{
//string ip = "192.168.1.134";
for(int j = ; j < ips.Length; j++)
{
if (!Ping(ips[j]))
{
count++;
listBox1.Items.Add(ips[j] + "失败"+count);
Application.DoEvents();
if (count == ) {
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 = ; 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 = ;
}
else
{
j--;
}
}
else
{
listBox1.Items.Add(ips[j] + "成功");
Application.DoEvents();
count = ;
}
} } 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[] + "','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 > * * )
{
/**/
///文件超过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(, 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();
} }
}
}

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

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

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

C# 自动Ping 测试服务器运行状况的更多相关文章

  1. 【Azure 应用服务】App Service 运行状况健康检查功能简介 (Health check)

    通过Azure App Service门户,启用Health Check来监视应用服务的实例,当发现其中一个实例处于不健康(unhealthy)状态时,通过重新路由(即把有问题的实例从负载均衡器中移除 ...

  2. 你真的了解 MySQL 数据库的运行状况吗?

    2015年第三方市场调查机构 Evans 数据公司最近公布的一系列客户调查数据显示,在过去两年里,MySQL 在所有开发者使用的数据库中获得了25%的市场份额,Evans 公司的本次调查显示,数据库的 ...

  3. 使用VisualVM分析tomcat运行状况(1)

    VisualVM是一款java程序性能分析与调优工具,而且还是jdk中自带的工具之一. tomcat也是一个java程序,自然也可以用它来进行监控.不过这里还是会有些问题,tomcat有两种常用的期待 ...

  4. 遇到问题无法在线上 debug,难道只能通过加日志再重新发布吗? 线上遇到某个用户的数据处理有问题,但线上同样无法 debug,线下无法重现! 是否有一个全局视角来查看系统的运行状况? 有什么办法可以监控到JVM的实时运行状态?

    https://alibaba.github.io/arthas/ Arthas 是Alibaba开源的Java诊断工具,深受开发者喜爱. 当你遇到以下类似问题而束手无策时,Arthas可以帮助你解决 ...

  5. 微服务中的健康监测以及其在ASP.NET Core服务中实现运行状况检查

    1 .什么是健康检查? 健康检查几乎就是名称暗示的.它是一种检查您的应用程序是否健康的方法.随着越来越多的应用程序转向微服务式架构,健康检查变得尤其重要(Health Check).虽然微服务架构有很 ...

  6. 【docker】【mysql】docker安装mysql,阿里云docker镜像加速器,docker搜索查看远程仓库上的镜像,docker拉取镜像,查看本地所有镜像,查看容器的运行状况,查看容器的详细信息

    在docker上安装mysql有两种方式 1.通过Dockerfile构建 2.直接在docker hub上拉取镜像安装 =================本篇采用方法2=============== ...

  7. SharePoint运行状况分析器有关磁盘空间不足的警告

    对于负责管理SharePoint内部部署安装的SharePoint管理员,SharePoint Health Analyzer是一款出色的工具.此功能不仅有助于解决服务器故障和服务失败的问题,还提供了 ...

  8. 使用 Apachetop 实时监测web服务器运行状况

    转自 http://42.96.169.71/blog/2013/01/26/shi-yong-apachetop-shi-shi-jian-ce-webfu-wu-qi-yun-xing-zhuan ...

  9. 监控 SQL Server (2005/2008) 的运行状况

    Microsoft SQL Server 2005 提供了一些工具来监控数据库.方法之一是动态管理视图.动态管理视图 (DMV) 和动态管理函数 (DMF) 返回的服务器状态信息可用于监控服务器实例的 ...

随机推荐

  1. (原)解决.NET 32位程序运行在64位操作系统下的兼容性问题

    背景:一个第三方组件是C++.NET  32位开发的,后被C#(基于FrameWork4.0)调用并封装成组件,此二次封装的组件无法运行于64位操作系统上.        开发环境:VS2012:解决 ...

  2. UIPickerView理解

  3. sql例子

    select * from plat_material_resource where stl_url LIKE '/data1/upload%' --截取字符串 UPDATE plat_materia ...

  4. jquery 时间戳与日期转换

    (function($) { $.extend({ myTime: { /** * 当前时间戳 * @return <int> unix时间戳(秒) */ CurTime: functio ...

  5. Oracle总结

    摘自:http://www.cnblogs.com/linjiqin/category/283838.html oracle decode用法 select decode( x , 1 , ‘x is ...

  6. JQuery全选Prop(“check”,true)和attr("attr",true)区别

    $scope.selectAll = false; //点击单选框的时候是不是全选 $scope.checkIsAll = function(){ var wipeCheckBoxObj = $(&q ...

  7. Ubuntu 16.04 LTS发布

    [Ubuntu 16.04 LTS发布]Ubuntu 16.04 LTS 发布日期已正式确定为 2016 年 4 月 21 日,代号为 Xenial Xerus.Ubuntu16.04 将是非常受欢迎 ...

  8. SpringMVC操作指南-整合Spring、SpringMVC、Hibernate、JUnit、Log4j、C3P0

  9. Cen0S下挂载设备

    在CentOS中,如果我们要查看光驱,U盘或者要把安装包挂载到某个文件夹,我写下我的一些理解. 所谓的挂载,就是把物理设备或者文件(包含安装文件,压缩包等等),与系统中的某个目录建立一个快捷方式,然后 ...

  10. Node.js的特点

    作为后端JavaScript的运行平台,Node保留了前端JavaScript中些熟悉的接口,没有改写语言本身的任何特性,依旧基于作用域和原型链,区别在于它将前端中广泛应用的思想作用到了服务器端.下面 ...