Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get ssl certificate details using python

I am using the following code to validate the ssl certificate status, Can we get more details about certificate like common name (CN),expiry date and issuer using request module or urllib

import requests

def check_ssl(url):
    try:
        req = requests.get(url, verify=True)
        print url + ' has a valid SSL certificate!'
    except requests.exceptions.SSLError:
        print url + ' has INVALID SSL certificate!'

check_ssl('https://google.com')
check_ssl('https://example.com')
like image 446
mikegray.397 Avatar asked Jan 12 '17 18:01

mikegray.397


People also ask

How do I view SSL certificate details?

To check an SSL certificate on any website, all you need to do is follow two simple steps. First, check if the URL of the website begins with HTTPS, where S indicates it has an SSL certificate. Second, click on the padlock icon on the address bar to check all the detailed information related to the certificate.

How do I verify a certificate in Python?

Certification holders may now have others easily verify their certification status by using a unique certificate verification code. The code can be found in the top right-hand corner on all digital certificates issued by the Python Institute.

What is SSL certificate Python?

Source code: Lib/ssl.py. This module provides access to Transport Layer Security (often known as “Secure Sockets Layer”) encryption and peer authentication facilities for network sockets, both client-side and server-side. This module uses the OpenSSL library.


1 Answers

import socket
import ssl
import datetime

domains_url = [
"devnote.in",
"devnote_wrong.in",
"stackoverflow.com",
"stackoverflow.com/status/404"
]

def ssl_expiry_datetime(hostname):
    ssl_dateformat = r'%b %d %H:%M:%S %Y %Z'

    context = ssl.create_default_context()
    context.check_hostname = False

    conn = context.wrap_socket(
        socket.socket(socket.AF_INET),
        server_hostname=hostname,
    )
    # 5 second timeout
    conn.settimeout(5.0)

    conn.connect((hostname, 443))
    ssl_info = conn.getpeercert()
    # Python datetime object
    return datetime.datetime.strptime(ssl_info['notAfter'], ssl_dateformat)

if __name__ == "__main__":
    for value in domains_url:
        now = datetime.datetime.now()
        try:
            expire = ssl_expiry_datetime(value)
            diff = expire - now
            print ("Domain name: {} Expiry Date: {} Expiry Day: {}".format(value,expire.strftime("%Y-%m-%d"),diff.days))
        except Exception as e:
            print (e)

#Output :

Domain name: devnote.in Expiry Date: 2020-11-11 Expiry Day: 46
[Errno -2] Name or service not known
Domain name: stackoverflow.com Expiry Date: 2020-11-05 Expiry Day: 41
[Errno -2] Name or service not known
like image 99
Fefar Ravi Avatar answered Sep 29 '22 07:09

Fefar Ravi