Help us understand the problem. What is going on with this article?

証明書期限切れまであと何日かチェックする

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)

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

qiita.comの証明書はあと106日後に切れる

参考URL

ssl.get_server_certificateで証明書を取得できない場合の対処 - Qiita

ssl --- ソケットオブジェクトに対する TLS/SSL ラッパー — Python 3.8.1 ドキュメント

Python サイトのSSL証明書の有効期限を取得する - Symfoware

SSL証明書の期限取得 - Qiita

x509証明書 - 雑多なメモ置き場

無題メモランダム: PythonでX日前/X日後を求める方法

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away