SoFunction
Updated on 2025-04-13

How to get SSL certificate information and expiration time of a domain name in Python

Understand the basic concepts of SSL certificates

First, the SSL (Secure Sockets Layer) certificate provides an encrypted connection to the website. During the data transmission process, it ensures the security of user information. An SSL certificate contains a lot of information, such as the certificate holder, validity period, and issuing authority. When you see the green lock logo in your browser, congratulations, you are visiting a website that uses an SSL certificate!

Then, sometimes we need to check the status of this certificate, such as its expiration time. As a powerful programming language, Python can help us easily obtain this information.

Use Python library to grab SSL certificate information

To obtain SSL certificate information, we first need some Python libraries. The most commonly used are ssl and socket. These two libraries can help us establish a connection to the server and obtain an SSL certificate. We can then also use the datetime library to handle date and time-related operations.

Install the necessary libraries

Before you start, make sure you have Python installed in your environment and you can use these libraries. In most cases, ssl and socket are standard libraries for Python, so no additional installation is required. But if you need to deal with some other formats, consider installing cryptography and OpenSSL.

pip install cryptography

Write code to obtain SSL certificate information

Next, write a simple Python script to get the SSL certificate information for the domain name we are interested in. Here is a basic code example:

import socket
import ssl
from datetime import datetime

def get_ssl_expiry_date(domain):
    port = 443  # SSL default port    ctx = ssl.create_default_context()
    with socket.create_connection((domain, port)) as sock:
        with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
            certificate = ()
            # Get validity period            expiry_date = certificate['notAfter']
            return expiry_date

if __name__ == '__main__':
    domain = input("Please enter the domain name you want to query:")
    expiry_date = get_ssl_expiry_date(domain)
    print(f"{domain} of SSL The certificate expiration time is:{expiry_date}")

Code interpretation

In the code, first, we import the necessary libraries. Then a function get_ssl_expiry_date is defined, which accepts a domain name as a parameter. We specify the default port 443 of SSL in the function. Next, we use the create_connection method to establish a connection to the domain name and SSL processing through the wrap_socket method.

After obtaining the certificate, we can extract the expiration time information from it. The format of this expiration time is generally YYYYMMDDHHMMSS, which is convenient for us to make the next date judgment.

Run the code to get the results

After running this script, you can enter any domain name you want to query, for example. The program will output the expiration time of the SSL certificate for the domain name.

Process and display certificate information

Of course, in addition to the expiration time, we can also extract some other certificate information, such as signature algorithms, issuing units, etc. It can be obtained through the certificate dictionary:

def display_certificate_info(certificate):
    print(f"Certificate Issuer: {certificate['issuer']}")
    print(f"The validity period of the certificate begins: {certificate['notBefore']}")
    print(f"The validity period of the certificate ends: {certificate['notAfter']}")
    print(f"Signature Algorithm Used: {certificate['signatureAlgorithm']}")

Just add this code to our main program to obtain the expiration time and output other relevant certificate information.

Check whether the certificate is about to expire

Sometimes it is important to monitor the expiration of SSL certificates. For example, you may need to remind yourself to renew or update some time before the certificate expires. You can determine whether the certificate is about to expire based on the expiration time:

def check_ssl_expiry(expiry_date):
    expiry_datetime = (expiry_date, "%b %d %H:%M:%S %Y %Z")
    if expiry_datetime < ():
        print("The certificate has expired!")
    elif (expiry_datetime - ()).days < 30:
        print("The certificate is about to expire, please be aware!")
    else:
        print("The certificate is valid and the status is normal.")

Integrate complete code

Finally, the various parts can be integrated together to form a complete SSL certificate checking script:

import socket
import ssl
from datetime import datetime

def get_ssl_expiry_date(domain):
    port = 443
    ctx = ssl.create_default_context()
    with socket.create_connection((domain, port)) as sock:
        with ctx.wrap_socket(sock, server_hostname=domain) as ssock:
            return ()

def display_certificate_info(certificate):
    print(f"Certificate Issuer: {certificate['issuer']}")
    print(f"The validity period of the certificate begins: {certificate['notBefore']}")
    print(f"The validity period of the certificate ends: {certificate['notAfter']}")
    print(f"Signature Algorithm Used: {certificate['signatureAlgorithm']}")

def check_ssl_expiry(expiry_date):
    expiry_datetime = (expiry_date, "%b %d %H:%M:%S %Y %Z")
    if expiry_datetime < ():
        print("The certificate has expired!")
    elif (expiry_datetime - ()).days < 30:
        print("The certificate is about to expire, please be aware!")
    else:
        print("The certificate is valid and the status is normal.")

if __name__ == '__main__':
    domain = input("Please enter the domain name you want to query:")
    certificate = get_ssl_expiry_date(domain)
    display_certificate_info(certificate)
    check_ssl_expiry(certificate['notAfter'])

Run this comprehensive script, you can not only obtain the expiration time of the SSL certificate, but also learn about various related information to ensure that your site is always running in a safe state.

Summarize

Through this method, it is not complicated to obtain information about SSL certificates using Python. Only a few lines of code can be used to monitor and check the domain name SSL certificate. I hope you can benefit from it and make your website safer in the ocean of the Internet!

The above is the detailed content of how Python obtains SSL certificate information and expiration time. For more information about Python obtaining SSL information for domain names, please follow my other related articles!