Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding timeout while fetching server certs via python

I am trying to fetch a list of server certificates 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.

like image 502
Amistad Avatar asked Sep 17 '25 02:09

Amistad


2 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)
like image 90
CasualDemon Avatar answered Sep 18 '25 17:09

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}")
like image 40
Michael Behrens Avatar answered Sep 18 '25 16:09

Michael Behrens