Python Tutorials - Herong's Tutorial Examples - v2.21, by Herong Yang
Use pyOpenSSL for HTTPS Connection
This section provides a tutorial example on using the OpenSSL.SSL module to create an HTTPS connection.
If you want to control the HTTPS connection at a lower level, you can use the OpenSSL.SSL module provided in the pyOpenSSL package as shown in this Python example script:
#- pyOpenSSL-SSL-test.py
#- Copyright (c) 2025 HerongYang.com. All Rights Reserved.
import sys
host = sys.argv[1]
from OpenSSL import SSL
context = SSL.Context(SSL.TLSv1_2_METHOD)
import socket
sock = socket.socket()
conn = SSL.Connection(context, sock)
conn.connect((host, 443))
conn.do_handshake()
print("\nCipher info:")
print(conn.get_cipher_name())
print(conn.get_cipher_version())
print(conn.get_cipher_bits())
print("\nServer certificate info:")
cert = conn.get_peer_certificate()
print("Subject = "+cert.get_subject().CN)
print("Issuer = "+cert.get_issuer().CN)
print("\nServer certificate chain:")
chain = conn.get_peer_cert_chain()
i = 0
for cert in chain:
i += 1
print("Cert "+str(i)+": Subject = "+cert.get_subject().CN)
print("Cert "+str(i)+": Issuer = "+cert.get_issuer().CN)
request = b"GET /\r\nHost: example.com\r\nConnection: close\r\n\r\n"
conn.sendall(request)
print("\nServer response:")
res = conn.recv(64)
print(res)
conn.shutdown()
conn.close()
There are several OpenSSL.SSL methods used in this script:
Here is what I get from the script on my old Ubuntu computer. You may need to install the pyOpenSSL package before running the script.
herong$ python --version
Python 2.7.10
herong$ pip install pyopenssl
Successfully installed cffi-1.15.1 cryptography-3.3.2
enum34-1.1.10 ipaddress-1.0.23 pycparser-2.21
pyopenssl-21.0.0 six-1.17.0
herong$ python pyOpenSSL-SSL-test.py www.google.com
Cipher info:
ECDHE-RSA-CHACHA20-POLY1305
TLSv1.2
256
Server certificate info:
Subject = www.google.com
Issuer = WR2
Server certificate chain:
Cert 1: Subject = www.google.com
Cert 1: Issuer = WR2
Cert 2: Subject = WR2
Cert 2: Issuer = GTS Root R1
Cert 3: Subject = GTS Root R1
Cert 3: Issuer = GlobalSign Root CA
Server response:
HTTP/1.0 200 OK
Date: Sat, 02 May 2026 19:37:58 GMT
Expires: -
Table of Contents
Variables, Operations and Expressions
Function Statement and Function Call
List, Set and Dictionary Comprehensions
Packages and Package Directories
"pathlib" - Object-Oriented Filesystem Paths
"pip" - Package Installer for Python
SciPy.org - Python Libraries for Science
pandas - Data Analysis and Manipulation
►Communicating with HTTPS Servers
http.client for HTTPS Connection
Retrieving SSLSocket Information
►Use pyOpenSSL for HTTPS Connection
Generating EC Public-Private Keys
Anaconda - Python Environment Manager