defget_ssl_expiry_date(host, port=443): """ get notAfter data from server cert """ cert = ssl.get_server_certificate((host, port)) x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert) return x509.get_notAfter().decode()
运行后,得到的过期时间样式为:
1
'20220219235959Z'
这是个UTC时间的字符串,也可以再来个脚本,转化下这个时间:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import datetime from pytz import timezone
# conf SRC_TZ = 'UTC' DST_TZ = 'Asia/Shanghai'
defload_ssl_date(dt_string, pattern='%Y%m%d%H%M%SZ'): """ convert ssl date from string to datetime obj """ src_tz = timezone(SRC_TZ) dst_tz = timezone(DST_TZ) dt = src_tz.localize(datetime.datetime.strptime(dt_string, pattern)) return dt.astimezone(tz=dst_tz)