python3-检测证书是否有效

import os
import pprint
import socket, ssl
from ssl import SSLError
import urllib.request


class CrerHandler:

    def __init__(self):
        pass

    def chek_init(self, url: str = None, pempath: str = None):
        if not url:
            url = 'https://curl.haxx.se/ca/cacert.pem'
        if not pempath:
            pempath = 'cacert.pem'
        isExists = os.path.exists(pempath)
        if not isExists:
            print("download file key.......")
            LoadPath = "{}".format(pempath)
            urllib.request.urlretrieve(url, LoadPath)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ssl_sock = ssl.wrap_socket(sock, ca_certs="cacert.pem", cert_reqs=ssl.CERT_REQUIRED)
        return ssl_sock

    def chek_ssl(self, sockt: object, domains: list, port: int = 443):
        if not sockt:
            print("不能传入为空")

        for domain in domains:
            try:
                sockt.connect((domain, port))
                print("{}:{} 域名:证书正常".format(domain, port))
                # print(repr(sockt.getpeername()))
                # print(sockt.cipher())
                # print(pprint.pformat(sockt.getpeercert()))
                write_arg = "HEAD / HTTP/1.0\r\nHost: {}\r\n\r\n".format(domain)
                sockt.sendall(bytes(write_arg, encoding='utf-8'))
            except SSLError:
                print('{}:{}证书错误或者SSL端口不正确'.format(domain, port))
            except ConnectionRefusedError:
                print("{}:{}无法连接服务器或端口未开放".format(domain, port))
            except TimeoutError:
                print('{}:{}连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。'.format(domain, port))
            except ValueError:
                print("{}:{}传入的域名的值不正确".format(domain, port))


if __name__ == "__main__":
    crer_handler = CrerHandler()
    socket_conn = crer_handler.chek_init()
    crer_handler.chek_ssl(socket_conn, ['1.1.1.1'], port=444)

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注