Reference library

Automation & scripting

CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.

31 matches
Automation & scripting medium

Build a Python Tool to Find All API Endpoints on a Website

A Python script that crawls a website, searches for common API endpoint patterns in HTML and JavaScript, and returns all discovered public API URLs.

api web-crawling automation
Python
import re
import requests
from urllib.parse import urljoin, urlparse
from collections import deque

def find_api_endpoints(base_url, max_pages=10):
    visited = set()
    queue = deque([base_url])
    api_endpoints = set()
    
    api_patterns = [
        r'/api/[a-zA-Z0-9_/-]+',
        r'/v[0-9]+/[a-zA-Z0-9_/-]+',…
52 0 Open
Automation & scripting easy

Check Service Ping Status and Exit Code in Python

Ping a list of hosts, print OK/FAIL per host, and exit with a non-zero code when any host is unreachable.

subprocess ping exit-code
Python
import subprocess
import sys

SERVICES = [
    "8.8.8.8",
    "1.1.1.1",
    "invalid-host",
]

def main():
    failed = []
    for host in SERVICES:
        result = subprocess.run(
            ["ping", "-c", "1", "-W", "2", host],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL,
        …
16 0 Open
Automation & scripting medium

Convert DOCX to Text by Unzipping XML in Python

Extract plain text from a .docx file by unzipping the container and parsing word/document.xml with regex, using only Python's standard library.

docx zipfile xml
Python
import zipfile
import re
from pathlib import Path

def docx_to_text_unzip_xml(docx_path: str) -> str:
    """Extract plain text from a .docx file by unzipping and parsing document.xml."""
    docx_path = Path(docx_path)
    if not docx_path.exists():
        raise FileNotFoundError(f"File not found: {docx_path}")

   …
12 0 Open
Automation & scripting medium

Detect Circular Imports Across Python Projects Automatically

This script walks through all .py files in a directory, builds an import graph, and uses depth-first search to find cycles—printing each circular dependency chain.

circular-imports import-graph ast
Python
import ast
import sys
from pathlib import Path
from collections import defaultdict, deque

def find_imports(filepath):
    """Return set of module names imported by a Python file."""
    imports = set()
    try:
        with open(filepath) as f:
            tree = ast.parse(f.read())
    except (SyntaxError, UnicodeDe…
39 0 Open
Automation & scripting medium

Extract Attachments from mbox Mailbox Files in Python

Extract file attachments from an mbox mailbox format using Python's standard library email and mailbox modules.

mbox email attachments
Python
import email
import mailbox
from email.policy import default
from pathlib import Path

def extract_attachments(mbox_path, output_dir):
    output_dir = Path(output_dir)
    output_dir.mkdir(exist_ok=True)
    mbox = mailbox.mbox(mbox_path)
    
    for msg in mbox:
        if msg.is_multipart():
            for part i…
13 0 Open
Automation & scripting medium

Find All Redirects on a Website in Python

Crawl a website from a starting URL, follow links within the same domain, and detect every HTTP redirect (301, 302, 303, 307, 308) using requests with redirects disabled.

redirects crawling requests
Python
import requests
from urllib.parse import urljoin, urlparse
from collections import deque

def find_redirects(start_url, max_pages=50):
    visited = set()
    redirects = {}
    queue = deque([start_url])
    
    while queue and len(visited) < max_pages:
        url = queue.popleft()
        if url in visited:
      …
38 0 Open
Automation & scripting medium

Find Best Meeting Time Across Time Zones in Python

This code calculates overlapping available hours among participants in different time zones and returns the best meeting time in UTC and each participant's local time.

timezones scheduling datetime
Python
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from dataclasses import dataclass
from typing import List, Tuple, Optional

@dataclass
class Participant:
    name: str
    timezone: str
    # weekdays availability: 0=Mon, start_hour (0-23), end_hour (0-23)
    available_slots: List[Tup…
39 0 Open
Automation & scripting medium

Find Sensitive Information in Log Files with Python

Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.

regex security log-analysis
Python
import re
import os
from pathlib import Path

def find_sensitive_info(log_path):
    """Scans log files for patterns like emails, IPs, API keys, and passwords."""
    patterns = {
        'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
        'API Key'…
37 0 Open
Automation & scripting easy

Generate Random Fake User Data for Testing in Python

This code generates a list of fake user dictionaries with random names, emails, ages, and timestamps using the Python standard library for testing purposes.

testing random data-generation
Python
import json
import random
import string
from datetime import datetime, timedelta

def generate_user_data(num_users=1):
    first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
    last_names = ["Smith", "Johnson", "Brown", "Taylor", "Wilson"]
    domains = ["example.com", "test.org", "demo.net"]
    
    users = …
39 0 Open
Automation & scripting medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
37 0 Open
Automation & scripting easy

Generate a Monthly Report CSV from Log Files in Python

Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.

csv logs report
Python
import csv
from collections import defaultdict
from datetime import datetime

def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
    events_by_date = defaultdict(int)
    revenue_by_date = defaultdict(float)
    
    with open(log_file, 'r') as f:
        for line in f:
            date_…
14 0 Open
Automation & scripting medium

How to Build a Python Tool That Finds Trending Open Source Projects Daily

A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.

github api trending
Python
import requests
import json
import datetime

def fetch_trending_projects(language: str = "", since: str = "daily"):
    url = "https://api.github.com/search/repositories"
    date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
    query = f"created:>{date_limit} language:{language}" if langua…
46 0 Open
Automation & scripting easy

How to Build an argparse CLI That Filters File Lines by Keyword in Python

This Python script is a command-line tool built with argparse that reads a text file and prints only the lines that contain (or don't contain) a given keyword.

argparse cli filter
Python
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Filter lines from a file by keyword.")
    parser.add_argument("input", type=str, help="File to read")
    parser.add_argument("keyword", type=str, help="Keyword to filter lines")
    parser.add_argument("--contains", action="sto…
14 0 Open
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 easy

How to Compress a Folder in Python While Preserving Directory Structure

A Python function that uses zipfile to recursively compress a folder, maintaining the original directory hierarchy inside the zip archive.

compression zipfile file-archiving
Python
import os
import zipfile
from pathlib import Path

def compress_folder(source_dir: str, output_zip: str):
    """
    Compress a folder into a zip file, preserving the directory structure.
    
    Args:
        source_dir: Path to the source directory to compress
        output_zip: Path for the output zip file
    "…
35 0 Open
Automation & scripting easy

How to Filter Docker Containers for Pruning in Python

Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.

docker json datetime
Python
import json
from datetime import datetime, timedelta


def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
    containers = json.loads(json_output)
    cutoff = datetime.now() - timedelta(hours=older_than_hours)
    return [
        c for c in containers
        if datetime.fromisoformat(c["crea…
13 0 Open
Automation & scripting easy

How to Generate Thumbnails While Maintaining Aspect Ratio in Python

Resize images to fit within maximum dimensions while preserving the original aspect ratio using Pillow (PIL).

pillow image-processing thumbnail
Python
from PIL import Image

def thumbnail_with_aspect_ratio(image_path, output_path, max_width, max_height):
    with Image.open(image_path) as img:
        # Get original dimensions
        width, height = img.size

        # Calculate scaling ratio to fit within max dimensions
        ratio = min(max_width / width, max_h…
13 0 Open
Automation & scripting medium

How to Implement a Weighted DNS Resolver with Failover in Python

Simulates a weighted DNS load balancer that distributes traffic across IPs by weight and automatically fails over when a server is marked unhealthy.

dns load-balancing failover
Python
import random
import time

class WeightedDNSResolver:
    def __init__(self, records):
        self.records = records  # list of (ip, weight)
        self.total_weight = sum(weight for _, weight in records)
        self.failed_ips = set()

    def resolve(self):
        available = [(ip, weight) for ip, weight in self…
13 0 Open
Automation & scripting easy

How to Mock a Whisper API Transcription Stub in Python

Simulate an OpenAI Whisper-style transcription response with a dataclass request model and a mock function that returns structured audio transcription output.

mock whisper api-stub
Python
import json
from dataclasses import dataclass
from typing import Optional

@dataclass
class AudioRequest:
    file_path: str
    language: Optional[str] = None

    def to_api_payload(self) -> dict:
        return {"file": self.file_path, "language": self.language}

def mock_whisper_transcribe(payload: dict) -> dict:
…
15 0 Open
Automation & scripting easy

How to Monitor Domain Expiration Dates in Python

A Python script that checks domain expiration dates using the python-whois library and warns when a domain is expiring soon.

whois domain automation
Python
import whois
from datetime import datetime, timedelta
import time

def check_domain_expiry(domain_name):
    """Check when a domain expires and warn if soon."""
    try:
        w = whois.whois(domain_name)
        expiry = w.expiration_date
        # Handle list or single date
        if isinstance(expiry, list):
   …
36 0 Open
Automation & scripting medium

How to Monitor Laptop Battery Health Over Time in Python

Log battery percentage, power status, and remaining time every N seconds to a JSON file using psutil for ongoing health monitoring.

psutil battery monitoring
Python
import time
import json
from pathlib import Path
from datetime import datetime

try:
    import psutil
except ImportError:
    print("psutil required: pip install psutil")
    exit(1)

LOG_FILE = Path("battery_health_log.json")

def monitor_battery(log_interval=60, duration=300):
    """Log battery percentage and rema…
39 0 Open
Automation & scripting easy

How to Scan Files Against a Malware Hash List in Python

Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.

hashlib file-scanning security
Python
import hashlib
from pathlib import Path

# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"

KNOWN_MALWARE_HASHES = {
    "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
    "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}

def sha25…
14 0 Open
Automation & scripting medium

How to Send an Email with smtplib and a Mock Server in Python

Send an email using smtplib and verify it with a local aiosmtpd mock SMTP server — perfect for testing without a real mail server.

smtplib email aiosmtpd
Python
import smtplib
from email.message import EmailMessage
import aiosmtpd.controller as controller
import threading


def handle_message(server, session, envelope):
    print(f"Mock server received message:")
    print(f"From: {envelope.mail_from}")
    print(f"To: {envelope.rcpt_tos}")
    print(f"Subject: {envelope.cont…
12 0 Open
Automation & scripting easy

How to Tail and Colorize Error Lines in Python

Reads the last N lines of a log file and prints error lines in red using ANSI color codes.

logging terminal colorize
Python
import sys
import time
from pathlib import Path

def tail_colorize(filename: str, lines: int = 20) -> None:
    """Read last N lines of a file, printing errors in red."""
    path = Path(filename)
    if not path.exists():
        print(f"File '{filename}' not found.", file=sys.stderr)
        return

    # Read last …
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Automation & scripting — Python code examples

What you will find here

This page collects automation & scripting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.