I am trying to capture the subject field as a string using the hostname. Like this:
/C=US/ST=California/L=Mountain View/O=Google LLC/CN=*.google.com
The same output can be obtained using
echo -n | openssl s_client -connect google.com:443 2>/dev/null | grep subject
subject=/C=US/ST=California/L=Mountain View/O=Google LLC/CN=*.google.com
Tried some subprocess module to get the above output but ended up falling on OpenSSL module to help me out because I am not well versed in Subprocess module. Using OpenSSL, I was able to get the desired output but it is returning it as an X509Name Object:
import socket, ssl
import OpenSSL
hostname = "google.com"
cert = ssl.get_server_certificate((hostname, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
print(x509.get_subject())
<X509Name object '/C=US/ST=California/L=Mountain View/O=Google LLC/CN=*.google.com'>
I want it to return this as a string. Can this be achievable?