Created
February 8, 2024 14:18
-
-
Save jimmy-ly00/e0f7ceda592783fbd398054c77ec85bf to your computer and use it in GitHub Desktop.
Extract common name from TLS certificate via URLs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ssl | |
import socket | |
from urllib.parse import urlparse | |
from cryptography import x509 | |
from cryptography.hazmat.backends import default_backend | |
def get_certificate_common_name(url, timeout=3): | |
# Parse the URL to get the hostname | |
parsed_url = urlparse(url) | |
hostname = parsed_url.hostname | |
# Connect to the host and get the SSL certificate | |
context = ssl.create_default_context() | |
context.check_hostname = False | |
context.verify_mode = ssl.CERT_NONE | |
with socket.create_connection((hostname, 443), timeout=timeout) as sock: | |
with context.wrap_socket(sock, server_hostname=hostname) as ssock: | |
cert_bin = ssock.getpeercert(binary_form=True) | |
# Parse the certificate and extract the common name (CN) | |
cert = x509.load_der_x509_certificate(cert_bin, default_backend()) | |
common_name = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)[0].value | |
return common_name | |
def print_certificate_common_name_for_urls(urls): | |
for url in urls: | |
try: | |
common_name = get_certificate_common_name(url) | |
print(f"The common name (CN) of the SSL certificate for {url} is: {common_name}") | |
except Exception as e: | |
print(f"Error processing {url}: {e}") | |
def main(): | |
urls = [ | |
"https://test1.com", | |
"https://test2.com", | |
] | |
print_certificate_common_name_for_urls(urls) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment