kumistatus/ssltools/__init__.py
2016-03-30 16:16:08 +02:00

30 lines
875 B
Python

import datetime, OpenSSL, socket, ssl
PEM = 0
DER = 1
DERBIN = 2
def getRemoteCert(host, port, form = PEM):
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
wrappedSocket = context.wrap_socket(sock, server_hostname=host)
try:
wrappedSocket.connect((host, port))
except:
return False
else:
if form == PEM:
response = ssl.DER_cert_to_PEM_cert(wrappedSocket.getpeercert(True))
elif form == DER:
response = wrappedSocket.getpeercert(False)
elif form == DERBIN:
response = wrappedSocket.getpeercert(True)
wrappedSocket.close()
return response
def getRemoteExpiry(host,port):
try:
return datetime.datetime.strptime(str(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, getRemoteCert(host, port)).get_notAfter().decode("UTF-8")), "%Y%m%d%H%M%SZ")
except:
pass