获取SSL证书链,并通过PyOpenSSL

时间:2019-03-27 10:56:31

标签: python python-2.7 openssl pyopenssl

我试图通过Python的OpenSSL库来计算SSL证书的到期日期。我是使用此库的新手,并在下面的代码中编写了计算到期日期的代码。但是,我总是得到证书为None。我只是不想运行此代码,而是还要安全地运行它。有人可以看看并建议我是否缺少任何步骤吗?谢谢

hostname = socket.getfqdn()
port = socket.gethostname().split('.')[0]
if port == 'master':
    port = 8140
else:
    port = 443

context = SSL.Context(SSL.SSLv23_METHOD)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_sock = SSL.Connection(context, sock)
ssl_sock.settimeout(10)
ssl_sock.connect((hostname, port))
ssl_sock.do_handshake()

certs = ssl_sock.get_peer_cert_chain()

if certs is not None:
    for cert in certs:
        x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
        subject = x509.get_subject()
        common_name = str(subject.CN)
        expire_date = x509.get_notAfter()

        datetimeformat = '%Y-%m-%d %H:%M:%S'

        current_date = datetime.datetime.now()
        cert_status = datetime.datetime.strptime(expire_date, datetimeformat) - datetime.datetime.strptime(
                                                                                        current_date, datetimeformat)
        cert_status = int(cert_status.days)
        dispatch_value('ssl_check', common_name, cert_status, 'gauge')

0 个答案:

没有答案