实现该功能,不用借助第三方库,用go的标准库就足够了..
以下程序可以获取这些域名的SSL证书的到期时间,并在证书距离现在不足7天过期时打印提示:
package main
import (
"crypto/tls"
"fmt"
"net"
"time"
)
func main() {
domains := []string{
"google.com",
"github.com",
"stackoverflow.com",
"amazon.com",
"microsoft.com",
"apple.com",
"netflix.com",
"facebook.com",
"twitter.com",
"linkedin.com",
}
for _, domain := range domains {
expirationDate, err := getCertificateExpirationDate(domain)
if err != nil {
fmt.Printf("Error getting certificate for %s: %v\n", domain, err)
continue
}
daysUntilExpiration := int(expirationDate.Sub(time.Now()).Hours() / 24)
if daysUntilExpiration <= 7 {
fmt.Printf("WARNING: Certificate for %s will expire in %d days (on %s)\n", domain, daysUntilExpiration, expirationDate.Format("2006-01-02"))
} else {
fmt.Printf("Certificate for %s will expire in %d days (on %s)\n", domain, daysUntilExpiration, expirationDate.Format("2006-01-02"))
}
}
}
func getCertificateExpirationDate(domain string) (time.Time, error) {
conn, err := tls.Dial("tcp", domain+":443", &tls.Config{
InsecureSkipVerify: true,
})
if err != nil {
return time.Time{}, err
}
defer conn.Close()
cert := conn.ConnectionState().PeerCertificates[0]
return cert.NotAfter, nil
}
执行代码,输出:
Certificate for google.com will expire in 61 days (on 2024-08-26)
Certificate for github.com will expire in 255 days (on 2025-03-07)
Certificate for stackoverflow.com will expire in 45 days (on 2024-08-09)
Certificate for amazon.com will expire in 196 days (on 2025-01-07)
Certificate for microsoft.com will expire in 354 days (on 2025-06-14)
Certificate for apple.com will expire in 63 days (on 2024-08-27)
Certificate for netflix.com will expire in 121 days (on 2024-10-24)
WARNING: Certificate for facebook.com will expire in 7 days (on 2024-07-02)
Certificate for twitter.com will expire in 157 days (on 2024-11-29)
Certificate for linkedin.com will expire in 35 days (on 2024-07-30)
对于A记录,其实都好说~
但是对于CNAME, 其实是有两套证书----
CNAME并不是301,访问 https://baidu.mydomain.com 时并不是跳转到 https://baidu.com/,而是https://baidu.mydomain.com的内容,和https://baidu.com/完全一样
所以对于此处, 如果我是mydomain.com的持有者和维护者, 我只需要关心 baidu.mydomain.com 的证书到期时间,而不用管baidu.com的证书到期时间 (虽然事实上,baidu
.mydomain.com的证书,也可以被baidu.com的维护者一起帮忙维护,但一般是mydomain.com的持有者自己维护)
所以,检测CNAME记录时,应该关心"baidu.mydomain.com"的证书到期时间,不用管"baidu.com"---这个是baidu那边的事情
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。