自动下载网站证书

112 阅读1分钟
#!/usr/bin/env python
# coding=utf-8

"""
<p>

</p>
@author: hai ji
@file: test.py
@date: 2024/6/12 
"""
import ssl
import socket


def get_certificate(hostname, port=443):
    context = ssl.create_default_context()
    with socket.create_connection((hostname, port)) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as ssock:
            der_cert = ssock.getpeercert(True)
            return ssl.DER_cert_to_PEM_cert(der_cert)


def save_certificate(cert, filename):
    with open(filename, 'w') as cert_file:
        cert_file.write(cert)


def download_certificate(url):
    if "https://" in url:
        hostname = url.split("https://")[1].split("/")[0]
    elif "http://" in url:
        hostname = url.split("http://")[1].split("/")[0]
    else:
        hostname = url.split("/")[0]

    cert = get_certificate(hostname)
    filename = f"{hostname}.crt"
    save_certificate(cert, filename)
    print(f"Certificate saved as {filename}")


if __name__ == "__main__":
    url = input("Enter the URL: ")
    download_certificate(url)