一个简单的代码片段:自动巡检SSL站点,收集监测列表里各个站点的SSL证书有效期。

原理:请求网站任一页面,在验证网站服务器证书的时候,读取证书的过期时间。并且,为了更快速获取响应结果,可以把超时时间适当调短,防止无响应的网站长时间挂起一次请求。在普通场景下,浏览器拿到Html以后需要加载各种引用的资源渲染页面,但是这个场景里不需要,使用HttpRequest(或其它httpclient)完成一次请求即可达到目的。


public static string HttpsCheck()
{
    string[] domains = JsonSerializer.Deserialize<string[]>(Strings.SSLDomains);
    Dictionary<string, string> dicDomains = new();
    Dictionary<string, Task> dicTasks = new();
    foreach (string domain in domains)
    {
        string url = $"https://{domain}";
        dicTasks[url] = Task.Run(() =>
        {
            HttpWebRequest request = WebRequest.CreateHttp(url);
            request.Timeout = 2000;
            request.ServerCertificateValidationCallback +=
                (object objSender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) =>
                {
                    if (sslPolicyErrors == SslPolicyErrors.None)
                    {
                        DateTime expdate = DateTime.Parse(certificate.GetExpirationDateString());
                        dicDomains[url] = expdate.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n剩余:" + (expdate - DateTime.Now).Days + "天";
                        return true;
                    }
                    else
                    {
                        dicDomains[url] = "证书错误";
                        return false;
                    }
                };
            try
            {
                request.GetResponse();
            }
            catch (Exception)
            {
                dicDomains[url] = "无法访问";
            }
        });
    }
    Task.WaitAll(dicTasks.Values.ToArray());
    return "SSL巡检结果:\r\n" + string.Join("\r\n\r\n", dicDomains.Select(kv => kv.Key + "\r\n" + kv.Value));
}

网页:

集成到公众号:

分类: articles