[PYTHON] Check for a few more days until the certificate expires

ssl_expire.py


import socket
import ssl
import OpenSSL

def get_server_certificate(hostname):
    context = ssl.create_default_context()
    with socket.create_connection((hostname, 443)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as sslsock:
            der_cert = sslsock.getpeercert(True)
            return ssl.DER_cert_to_PEM_cert(der_cert)

cert = get_server_certificate('qiita.com')
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert.encode('utf-8'))

import datetime
from datetime import datetime as dt
not_before = dt.strptime(str(x509.get_notBefore())[2:16],'%Y%m%d%H%M%S') + datetime.timedelta(hours=9)
not_after  = dt.strptime(str(x509.get_notAfter())[2:16],'%Y%m%d%H%M%S')  + datetime.timedelta(hours=9)
print(not_after)
aaa = not_after - dt.now()
print(aaa)
$ python3 ssl_expire.py
2020-04-30 21:00:00
106 days, 19:33:22.726942

The qiita.com certificate will expire in 106 days

Reference URL

What to do if you can't get the certificate with ssl \ .get \ _server \ _certificate -Qiita

ssl ---TLS / SSL wrapper for socket objects — Python 3 \ .8 \ .1 documentation )

Getting the SSL certificate expiration date for Python site -Symfoware

Getting the SSL certificate expiration date -Qiita

x509 certificate -miscellaneous memo storage

Untitled Memo Random: How to find X days before / X days after with Python

Recommended Posts

Check for a few more days until the certificate expires
[Data analysis for 5 years] Is the stock price rising a few days after the Golden Cross?
Find the dates for a jarring tournament
Change the list in a for statement