2022年5月8日 星期日

[研究][WinForm][C#]偵測網站是否 Service Unavailable並 Reboot

[研究][WinForm][C#]偵測網站是否 Service Unavailable並 Reboot

2022-05-08

環境:Visual Studio 2022 + C# + WinForm + Console

********************************************************************************

Program.cs

using System;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;

namespace CheckAndRestart
{
    class Program
    {
        static void Main(string[] args)
        {
            //方法三:使用System.Threading.Timer
            //Timer構造函數參數說明:
            //Callback:一個 TimerCallback 委托,表示要執行的方法。
            //State:一個包含回調方法要使用的信息的對象,或者為空引用(Visual Basic 中為 Nothing)。
            //dueTime:調用 callback 之前延遲的時間量(以毫秒為單位)。指定 Timeout.Infinite 以防止計時器開始計時。指定零 (0) 以立即啟動計時器。
            //Period:調用 callback 的時間間隔(以毫秒為單位)。指定 Timeout.Infinite 可以禁用定期終止。

            Program obj = new Program();
            //Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());

            // 1秒=1000毫秒,預計5分鐘監控一次
            System.Threading.Timer threadTimer = new System.Threading.Timer(new System.Threading.TimerCallback(obj.Method3), null, 0, 5 * 60 * 1000);
            // 測試觸發狀況
            //while (true)
            //{
            //    //Console.WriteLine("test_" + Thread.CurrentThread.ManagedThreadId.ToString());
            //    //Console.WriteLine(DateTime.Now.ToString());
            //    Thread.Sleep(100);
            //}

            /*
            // 忽略 https 憑證驗證
            // https://blog.alantsai.net/posts/2017/12/csharp-ssl-remote-validation-error
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

            // 讀取網頁內容
            string html = string.Empty;
            string url = "https://localhost";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.UserAgent = "C# console client";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            using (Stream stream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream))
            {
                html = reader.ReadToEnd();
            }
            //Service Unavailable
            //HTTP Error 503.The service is unavailable.
            //Console.WriteLine(DateTime.Now.ToString() + " 檢察網站是 Service Unavailable,是則重新啟動 Windows。");
            //Console.WriteLine(html);

            // 重新啟動 Windows 
            //System.Diagnostics.Process.Start("C:\\WINDOWS\\system32\\shutdown.exe", "-f -r -t 0");
            // 另一種方法
            //https://asd0961296920.pixnet.net/blog/post/318508838

            // https://king39461.pixnet.net/blog/post/400285133
            //ProcessStartInfo ps = new ProcessStartInfo();
            //ps.FileName = "shutdown.exe";
            //ps.Arguments = "-s -t 1";
            //Process.Start(ps);

            // http://www.blueshop.com.tw/board/FUM20050124192253INM/BRD2007032912332212M.html
            */
            Console.ReadLine();
        }
        void Method3(Object state)
        {
            Console.WriteLine(DateTime.Now.ToString() + " 每5分鐘檢察網站是 Service Unavailable,是則重新啟動 Windows。");
            //Console.WriteLine(DateTime.Now.ToString() + "_" + Thread.CurrentThread.ManagedThreadId.ToString());
            //Console.WriteLine(DateTime.Now.ToString());

            try
            {
                // 忽略 https 憑證驗證
                // https://blog.alantsai.net/posts/2017/12/csharp-ssl-remote-validation-error
                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

                // 讀取網頁內容
                string html = string.Empty;
                // 網路環境關係,不可用真實網址,用 localhost
 
                string url = "https://localhost";

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "C# console client";

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    html = reader.ReadToEnd();
                }


                //var client = new SmtpClient("smtp.gmail.com", 587)
                //var client = new SmtpClient("127.0.0.1", 25)
                var client = new SmtpClient("xxx.xxx.xxx.xxx", 25)
                {
                    //EnableSsl = true,
                    DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential("Email帳號", "密碼")
                    
                };
                //client.Send("測試信<xxx@gmail.com>", "to address", "test", "testbody");

                if (html.Contains("Service Unavailable"))
                {
                    client.Send("user1@abc.def", "user2@abc.def", "【XX網站】發現 Service Unavailable", "重新啟動 Windows");
Thread.Sleep(60 * 1000); // wait 1 minute for send email } // ReStart if (html.Contains("Service Unavailable")) { System.Diagnostics.Process.Start("C:\\WINDOWS\\system32\\shutdown.exe", "-f -r -t 0"); } } catch (Exception ex) { var client = new SmtpClient("xxx.xxx.xxx.xxx", 25) { //EnableSsl = true, DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, UseDefaultCredentials = false, //Credentials = new NetworkCredential("Email帳號", "密碼") }; client.Send("user1@abc.def", "user2@abc.def", "【XX網站】發現異常", "重新啟動 Windows");
Thread.Sleep(60 * 1000); // wait 1 minute for send email // 撈不到網站的網頁,也是 restart System.Diagnostics.Process.Start("C:\\WINDOWS\\system32\\shutdown.exe", "-f -r -t 0"); } //Console.WriteLine(html); } } }

(完)

相關

[研究][C#]呼叫 Windows Update 更新和 Reboot
https://shaurong.blogspot.com/2022/05/c-windows-update-reboot.html

[研究][WinForm][C#]偵測網站是否 Service Unavailable並 Reboot
https://shaurong.blogspot.com/2022/05/winformc-service-unavailable-reboot.html


沒有留言:

張貼留言