侧边栏壁纸
博主头像
cn2linux博主等级

行动起来,活在当下

  • 累计撰写 128 篇文章
  • 累计创建 1 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Python 检测证书是否有效

import os
import logging
import socket
import ssl
from ssl import SSLError
import urllib.request
import argparse

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')

class CertHandler:

    def __init__(self, pem_path='cacert.pem'):
        self.pem_path = pem_path

    def check_init(self, url='https://curl.haxx.se/ca/cacert.pem'):
        if not os.path.exists(self.pem_path):
            logging.info("Downloading certificate key...")
            urllib.request.urlretrieve(url, self.pem_path, self._download_progress)

    def _download_progress(self, count, block_size, total_size):
        percent = int(count * block_size * 100 / total_size)
        logging.info("Download progress: %d%%", percent)

    def check_domain_ssl(self, domain, port):
        try:
            with socket.create_connection((domain, port)) as sock:
                with ssl.wrap_socket(sock, ca_certs=self.pem_path, cert_reqs=ssl.CERT_REQUIRED) as ssl_sock:
                    write_arg = f"HEAD / HTTP/1.0\r\nHost: {domain}\r\n\r\n"
                    ssl_sock.sendall(write_arg.encode('utf-8'))
                    logging.info(f"{domain}:{port} 域名:证书正常")
        except SSLError as e:
            logging.error(f'{domain}:{port} 证书错误或者SSL端口不正确: {e}')
        except (ConnectionRefusedError, TimeoutError, ValueError) as e:
            logging.error(f"{domain}:{port} 连接错误: {e}")

    def check_ssl(self, domains, port=443):
        for domain in domains:
            self.check_domain_ssl(domain, port)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Check SSL certificate for given domains and port.")
    parser.add_argument('domains', type=str, help="Comma-separated list of domains to check, e.g., '1.1.1.1,2.2.2.2'")
    parser.add_argument('port', type=int, nargs='?', default=443, help="Port number, defaults to 443")
    args = parser.parse_args()

    domain_list = args.domains.split(',')
    cert_handler = CertHandler()
    cert_handler.check_init()
    cert_handler.check_ssl(domain_list, args.port)

0

评论区