【python】実際のサーバのSSL証明書を見に行って、残り日数を表示してみた。
参考URL
https://qiita.com/nnsnodnb/items/f51298ed8668be5d6abb
1 |
google.com Remain 55 days, Expire 2024-03-26 13:02:51 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import datetime import socket import ssl # SSL証明書の有効期限を調べて、結果を返す def post_slack(hostname): print( hostname + ssl_expires_in(hostname)) # 有効期限で振り分け def ssl_expires_in(hostname, buffer_days=30): # n日前で期限分岐 # 有効期限を取得 expires = ssl_expiry_datetime(hostname) # 残り日数を計算 remaining = expires - datetime.datetime.utcnow() remaining_days = remaining.days # もう切れていたら if remaining < datetime.timedelta(days=0): raise AlreadyExpired("Cert expired %s days ago" % remaining.days) # 残り少なかったら elif remaining < datetime.timedelta(days=buffer_days): return ' Remain ' + str(remaining_days) + ' days, Expire ' + str(expires) + ' Please Check Cert!!' else: return ' Remain ' + str(remaining_days) + ' days, Expire ' + str(expires) # 実際のサーバのSSL証明書の有効期限を調べる関数 def ssl_expiry_datetime(hostname): ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z' context = ssl.create_default_context() conn = context.wrap_socket( socket.socket(socket.AF_INET), server_hostname=hostname, ) conn.settimeout(3.0) conn.connect((hostname, 443)) ssl_info = conn.getpeercert() # ssl_info['notAfter'] が証明書の期限 return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt) # ココがスタート、ドメイン名を引数で渡す post_slack('google.com') |