最近遇到一些管理的憑證到期,忘記續約,後來決定寫一隻程式來檢查一下,因為很多管理端都不是在我這邊
所以有點麻煩,但是我得幫忙續約 :'(

這邊我就封裝成一個 function ,這樣就可以直接呼叫是否過期,如果要改寫就自行採用,可以在判斷 NotAfter 的部分
改寫成如果過期前幾天開始就發送提醒的通知,這邊就自行改寫吧,因為為了避免一些直接跟 host 產生的 shaking 問題
這邊後來我改成 httpclient 去模擬瀏覽器去抓取會比較準
public static void CheckSslCertificate(string url)
{
try
{
// 建立 HttpClientHandler 並攔截憑證驗證
using var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
var x509 = new X509Certificate2(cert);
Console.WriteLine("=== SSL 憑證資訊 ===");
Console.WriteLine("網站:" + url);
Console.WriteLine("主題:" + x509.Subject);
Console.WriteLine("頒發者:" + x509.Issuer);
Console.WriteLine("生效日:" + x509.NotBefore);
Console.WriteLine("到期日:" + x509.NotAfter);
Console.WriteLine("是否過期:" + (DateTime.Now > x509.NotAfter ? "是" : "否"));
Console.WriteLine("剩餘天數:" + (x509.NotAfter - DateTime.Now).TotalDays + " 天");
Console.WriteLine("====================");
return true;
};
using var client = new HttpClient(handler);
// 模擬瀏覽器 User-Agent,避免被 CDN 阻擋
client.DefaultRequestHeaders.Add(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
);
var task = client.GetAsync(url);
task.Wait();
var response = task.Result;
Console.WriteLine("HTTP 狀態碼: " + (int)response.StatusCode);
}
catch (Exception ex)
{
Console.WriteLine("發生錯誤:" + ex.Message);
}
}呼叫端
CheckSslCertificate("https://www.google.com");
CheckSslCertificate("https://blog.no2don.com");
//沒有SSL
CheckSslCertificate("https://no2don.com");
result:

reference:
程式碼部分採用 AI 輔助撰寫
---
請你暫時把你的勇氣給我 在夢想快消失的時候 讓我的 Code 用力的穿過天空 為愛我的人做一秒英雄 如果這篇文章有幫助到您,簡單留個言,或是幫我按個讚,讓我有寫下去的動力…
Yesterday I wrote down the code. I bet I could be your hero. I am a mighty little programmer.