Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

12 matches
Automation & scripting medium

How to Check SSL Certificate Expiry in Python

Connect to a host over TLS, extract the certificate's expiry date, and report days remaining using only the Python standard library.

ssl certificate socket
Python
import socket
import ssl
from datetime import datetime

def check_cert_expiry(hostname, port=443):
    context = ssl.create_default_context()
    with socket.create_connection((hostname, port), timeout=10) as sock:
        with context.wrap_socket(sock, server_hostname=hostname) as tls_sock:
            cert = tls_soc…
16 0 Open
Automation & scripting medium

How to Validate SSL Certificates for Multiple Domains in Python

A Python utility that checks SSL certificate expiry dates for a list of domains using the standard library ssl and socket modules.

ssl certificate validation
Python
import ssl
import socket
from datetime import datetime

def check_ssl_certificate(hostname: str, port: int = 443) -> dict:
    """Validate SSL certificate for a given hostname."""
    context = ssl.create_default_context()
    with socket.create_connection((hostname, port), timeout=5) as sock:
        with context.wra…
43 0 Open
Automation & scripting easy

Mock Certbot Renewal in Python for Testing

Simulates a Let's Encrypt certificate renewal by writing a mock certificate file and printing realistic certbot CLI output, without calling the actual certbot.

certbot letsencrypt automation
Python
import subprocess
import sys
from datetime import datetime, timedelta
from pathlib import Path


def renew_cert(domain: str, output_dir: str = "certs") -> str:
    """Simulate a Let's Encrypt renewal with mock certbot output."""
    out = Path(output_dir)
    out.mkdir(parents=True, exist_ok=True)

    cert_path = out…
16 0 Open
Microservices patterns medium

How to Handle mTLS Certificate Rotation in Python

Detect mTLS certificate file changes by tracking modification time and hot-reload the SSL context in a running service.

mtls ssl certificate-rotation
Python
import ssl
import tempfile
import datetime
from pathlib import Path


class MTLSContext:
    def __init__(self, cert_path, key_path, ca_path):
        self.cert_path = Path(cert_path)
        self.key_path = Path(key_path)
        self.ca_path = Path(ca_path)
        self.context = None
        self.last_loaded_mtime …
13 0 Open
Microservices patterns medium

How to Mock mTLS Between Services in Python

Simulate mutual TLS authentication between two services using Python's ssl module with self-signed certificates.

mtls ssl security
Python
import ssl
import socket
import threading
import tempfile
from pathlib import Path
import subprocess

def create_test_cert(cert_path: Path, key_path: Path, common_name: str = "localhost"):
    """Generate a self-signed certificate using openssl."""
    subprocess.run([
        "openssl", "req", "-x509", "-newkey", "rs…
15 0 Open
Auth & security at scale medium

ACME LetsEncrypt Mock Challenge Server in Python

A minimal HTTP server that serves key authorizations for ACME/Let's Encrypt DNS-01 or HTTP-01 challenges during testing and validation.

acme letsencrypt http-server
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

# In-memory store simulating the ACME challenge token -> key authorization pair
challenge_store = {
    "token_example": "token_example.key_authorization"
}

class AcmeChallengeHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        # Extra…
15 0 Open
Auth & security at scale medium

How to Mock Certificate Pinning with SPKI Hash in Python

Shows how to compute and compare a certificate's SubjectPublicKeyInfo SHA-256 hash for pinning validation in Python.

certificate ssl pinning
Python
import hashlib
import base64
import ssl
import socket

class MockCertificatePinner:
    """Demonstrates SPKI hash pinning for certificate validation."""
    
    def __init__(self, pinned_spki_hashes):
        self.pinned_hashes = set(pinned_spki_hashes)
    
    def get_spki_hash(self, cert_pem):
        """Compute t…
14 0 Open
Auth & security at scale easy

How to Mock a TLS Certificate Rotation Schedule in Python

Simulate a TLS certificate rotation schedule with a Python class that tracks last and next rotation dates and decides when to rotate.

tls certificates rotation
Python
import datetime
import random
import time


class CertRotator:
    def __init__(self, cert_name, rotation_days=30):
        self.cert_name = cert_name
        self.rotation_days = rotation_days
        self.last_rotated = datetime.date.today() - datetime.timedelta(days=random.randint(10, 25))
        self.next_rotatio…
16 0 Open
Auth & security at scale medium

How to Mock an mTLS Client Certificate in Python

Create a self-signed client certificate and key with OpenSSL, load them into an SSL context, and simulate an mTLS handshake in Python for testing.

mtls ssl certificates
Python
import ssl
import socket
import subprocess
import tempfile
from pathlib import Path

def create_mock_certificates():
    """Generate self-signed client certificate and key for mTLS testing."""
    with tempfile.TemporaryDirectory() as tmpdir:
        cert_path = Path(tmpdir) / "client.crt"
        key_path = Path(tmpd…
14 0 Open
Auth & security at scale medium

How to implement OCSP stapling mock in Python

Simulate OCSP stapling with a caching mechanism that mocks certificate status lookups for TLS handshake validation.

ocsp tls security
Python
import hashlib
import time

class OCSPStapler:
    def __init__(self, cert_serial: str, issuer_hash: str):
        self.cert_serial = cert_serial
        self.issuer_hash = issuer_hash
        self.cache = {}

    def _mock_query_ocsp(self, serial: str) -> dict:
        """Simulate OCSP responder lookup."""
        di…
12 0 Open
Auth & security at scale medium

How to mock DNS CAA record lookups in Python

Parse and filter DNS CAA records with a mock lookup function, demonstrating how certificate authorities validate domain authorization.

dns security caa
Python
import dnslib

def parse_caa_record(record_string):
    """Parse a DNS CAA record string into its components."""
    parts = record_string.split()
    flags = int(parts[0])
    tag = parts[1]
    value = parts[2]
    return flags, tag, value

def mock_caa_lookup(domain, caa_records):
    """Mock DNS CAA lookup that re…
18 0 Open
Production deployment patterns easy

How to Mock an Ingress TLS Certificate Manager in Python

Build a mock TLS certificate manager for ingress that issues, checks, and renews certificates with expiry tracking — useful for testing deployment workflows before touching real infrastructure.

tls certificates ingress
Python
import ssl
import socket
from datetime import datetime, timedelta


class TLSCertManager:
    def __init__(self, hostname):
        self.hostname = hostname
        self.certificates = {}

    def request_certificate(self, domain, days_valid=90):
        """Mock a certificate issuance request that stores a cert with e…
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.