Last active
February 18, 2018 20:39
-
-
Save kpavlovsky/4813aace09227889b069e8e6da7739f4 to your computer and use it in GitHub Desktop.
get certificate expiration time in days, python3.6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from OpenSSL import SSL | |
import socket | |
import datetime | |
import sys | |
def get_domain_certificate_expiration_days(domain: str, port: int=443) -> int: | |
cur_date = datetime.datetime.utcnow() | |
cert_tested = 0 | |
try: | |
context = SSL.Context(SSL.SSLv23_METHOD) | |
sock = SSL.Connection( | |
context, socket.socket(socket.AF_INET, socket.SOCK_STREAM)) | |
try: | |
sock.connect((str(domain), int(port))) | |
# sock.do_handshake() | |
sock.send("\x00") # Send empty to trigger response | |
get_peer_cert = sock.get_peer_certificate() | |
sock.close() | |
get_not_after = get_peer_cert.get_notAfter().decode('utf-8') | |
exp_date = datetime.datetime.strptime( | |
get_not_after, '%Y%m%d%H%M%SZ') | |
days_to_expire = int((exp_date - cur_date).days) | |
cert_tested = cert_tested + 1 | |
chain = sock.get_peer_cert_chain() | |
return days_to_expire | |
except Exception as e: | |
return str(e) | |
except SSL.Error as e: | |
return str(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment