python-3.xssl-certificatepyopenssl

how to do "openssl s_client -connect ip_addr:port -servername url" in python


Currently I am using this code to get the SSL certificate:

import socket
from OpenSSL import SSL
import requests
    
context = SSL.Context(method=SSL.SSLv23_METHOD)
for bundle in [requests.certs.where(), '/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem', '/etc/ssl/certs/ca-certificates.crt']:
    try:
        context.load_verify_locations(cafile=bundle)
    except Exception:
        pass

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssl_conn = SSL.Connection(context=context, socket=sock)
ssl_conn.set_tlsext_host_name(url.encode())
ssl_conn.settimeout(5)
ssl_conn.connect((url, port))
ssl_conn.setblocking(1)
ssl_conn.do_handshake()
peer_cert = ssl_conn.get_peer_certificate()

How can I replicate the command:

openssl s_client -connect ip_addr:port -servername url

Solution

  • import socket
    from OpenSSL import SSL
    import requests
    
    context = SSL.Context(method=SSL.SSLv23_METHOD)
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ssl_conn = SSL.Connection(context=context, socket=sock)
    ssl_conn.set_tlsext_host_name(hostname.encode())
    ssl_conn.settimeout(5)
    ssl_conn.connect((str(ip_addr), port))
    ssl_conn.setblocking(1) 
    ssl_conn.do_handshake()
    peer_cert = ssl_conn.get_peer_certificate()