Adding timeout while fetching server certs via python

Question:

I am trying to fetch a list of server certificates and using the python standard SSL library to accomplish this. This is how I am doing it:

import ssl
from socket import *

urls = [i.strip().lower() for i in open("urls.txt")]
for urls in url:
    try:
        print ssl.get_server_certificate((url, 443))
    except error:
        print "No connection"

However for some URLs,there are connectivity issues and the connection just times out.However it waits for the default ssl timeout value(which is quite long) before timing out.How do i specify a timeout in the ssl.get_server_certificate method ? I have specified timeouts for sockets before but I am clueless as to how to do it for this method

Asked By: Amistad

||

Answers:

From the docs:

SSL sockets provide the following methods of Socket Objects:

gettimeout(), settimeout(), setblocking()

So should just be as simple as:

import ssl
from socket import *

settimeout(10)

urls = [i.strip().lower() for i in open("urls.txt")]
for urls in url:
    try:
        print ssl.get_server_certificate((url, 443))
    except (error, timeout) as err:
        print "No connection: {0}".format(err)
Answered By: CasualDemon

This versions runs for me using with Python 3.9.12 (hat tip @bchurchill):

import ssl
import socket
socket.setdefaulttimeout(2)

urls = [i.strip().lower() for i in open("urls.txt")]
for url in urls:
    try:
        certificate = ssl.get_server_certificate((url, 443))
        print (certificate)
    except Exception as err:
        print(f"No connection to {url} due to: {err}")
Answered By: Michael Behrens
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.