I know how to get certificate information such as expiration date using pyopenssl for instance, but is it possible to do it with a aiohttp response object?
3 Answers
I couldn't find it in the documentation of aiohttp, but you can use ssl to get the cert and OpenSSL to get it's notAfter date and compare it to your current date in order to figure out if it's expired or not. More details here How to import OpenSSL in python And a snippet of code that does pretty much what you need below You will need to install OpenSSL beforehand however
pip install pyopenssl
import OpenSSL
import ssl
cert=ssl.get_server_certificate(('www.google.com', 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
x509.get_notAfter()
For sites that make use of SNI, see the following answer on how to get the certificate ssl.get_server_certificate for sites with SNI (Server Name Indication)

- 2,228
- 3
- 19
- 51

- 2,751
- 1
- 10
- 15
-
4You don't really need OpenSSL. [serverlescode](https://serverlesscode.com/post/ssl-expiration-alerts-with-lambda/) has an example that doesn't require it (too long to post as comment...) – Alessandro Dentella Aug 28 '17 at 09:24
-
2**Warning**: This does not work with SNI (multiple domain names on one IP) as it just fetches the certificate under that IP address, which might be a different one. See https://stackoverflow.com/questions/49132025/ssl-get-server-certificate-for-sites-with-sni-server-name-indication for a solution – Daniel F Aug 12 '18 at 09:58
-
1`socket` is never used. – Pedro Lobito Mar 03 '20 at 16:54
-
Note that this method is **not asynchronous** – Romuald Brunet Jul 21 '20 at 12:21
Previous answers are correct but, you could also use the socket lib (this is test with python 3.7)
from urllib.request import Request, urlopen, ssl, socket
from urllib.error import URLError, HTTPError
import json
#some site without http/https in the path
base_url = 'CHANGE_ME_TO_YOUR_SITE'
port = '443'
hostname = base_url
context = ssl.create_default_context()
with socket.create_connection((hostname, port)) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as ssock:
print(ssock.version())
data = json.dumps(ssock.getpeercert())
# print(ssock.getpeercert())
print (data)

- 21,260
- 6
- 105
- 81
-
3I prefer this answer, doesn't require pulling in an external package and the output is actually more sensible to me; why does OpenSSL require a method call to get_notAfter() and get_notBefore()? These should just be properties of the cert... – JTW Jun 28 '19 at 16:12
Check this repo called check-tls-certs. It's not really aiohttp, but it's based on asyncio and so it works asynchronously.

- 11
- 1
- 1