ssl.get_server_certificate can do this:
import ssl ssl.get_server_certificate(("www.sefaz.ce.gov.br",443))
I think the doc string function is more clear than the dyth python site:
"""Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt."""
Thus, you can extract the common name from the binary DER certificate to search for the common identifier of the object:
def get_commonname(host,port=443): oid='\x06\x03U\x04\x03' # Object Identifier 2.5.4.3 (COMMON NAME) pem=ssl.get_server_certificate((host,port)) der=ssl.PEM_cert_to_DER_cert(pem) i=der.find(oid) # find first common name (certificate authority) if i!=-1: i=der.find(oid,i+1) # skip and find second common name if i!=-1: begin=i+len(oid)+2 end=begin+ord(der[begin-1]) return der[begin:end] return None
source share