zoukankan      html  css  js  c++  java
  • 用C#的控制台程序监控apache网站是否正常

    自己随便写的,没用在真实环境上。仅供参考。


    添加一个应用

    选中 System.ServiceProcess

    下面是源代码

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.ServiceProcess;
    using System.Threading;

    namespace frey
    {
    class Program
    {
    static void Main(string[] args)
    {
    string pageUrl = "http://localhost/";

    bool istrue = false;

    while (true)
    {
    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(pageUrl);
    HttpWebResponse myHttpWebResponse; //=无法连接到远程服务器
    try
    {
    myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
    /*
    HttpStatusCode.OK 等效于 HTTP 状态 200。OK 指示请求成功,且请求的信息包含在响应中。这是最常接收的状态代码。
    HttpStatusCode.BadGateway 等效于 HTTP 状态 502。BadGateway 指示中间代理服务器从另一代理或原始服务器接收到错误响应。
    HttpStatusCode.NotFound 等效于 HTTP 状态 404。NotFound 指示请求的资源不在服务器上。
    */
    if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
    {
    istrue = true;
    }
    else
    {
    istrue = false;
    }
    myHttpWebResponse.Close();
    }
    catch (WebException ex)
    {
    istrue = false;
    Console.WriteLine(ex.Status); //ConnectFailure
    }
    //判断网站是否正常
    Console.WriteLine(istrue.ToString());
    //不正常重启APACHE服务
    if (istrue == false)
    {
    ServiceController sc = new ServiceController();
    sc.ServiceName = "apache2.2";
    if (sc.CanStop)
    {
    if (sc.Status == ServiceControllerStatus.Running)
    {
    sc.Stop();
    Console.WriteLine("停止apahe服务器");
    }
    }
    Console.WriteLine(sc.Status);
    if (sc.Status == ServiceControllerStatus.Stopped)
    {
    try
    {
    sc.Start();
    Console.WriteLine("时间:{0}", DateTime.Now.ToString());//时间
    Console.WriteLine("启动apahe服务器");
    }
    catch { }
    }
    sc.Close();
    }
    Thread.Sleep(6000);
    Console.WriteLine("6秒"); //每6秒检测一次,实际环境可设为60秒或更多
    }
    }
    }
    }

    希望大家给出意见。

    自己感觉不足的地方,一是超时没有判断。二是对apache的假死还没想到合适的办法。

  • 相关阅读:
    三角函数
    第十七次作业
    第十六次作业
    第15次作业
    第13次java作业
    第十二次java作业
    第十一次java作业
    第十次java作业
    第九次java
    第八次java作业
  • 原文地址:https://www.cnblogs.com/frey/p/2323748.html
Copyright © 2011-2022 走看看