Reference library

Automation & scripting

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

21 matches
Automation & scripting easy

Aggregate Log Errors Count by Hour in Python

Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.

logs regex counter
Python
import re
from collections import Counter
from datetime import datetime

def aggregate_errors_by_hour(log_lines):
    pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
    hourly_counts = Counter()
    
    for line in log_lines:
        match = pattern.match(line)
        if match:
            ho…
21 0 Open
Automation & scripting easy

Build a Live Countdown Timer for Events in Python

A Python script that displays a real-time countdown to a target date and time, updating every second in the console.

datetime countdown timers
Python
import datetime
import time

def countdown(event_name, target_datetime):
    """Displays a live countdown to a target datetime."""
    while True:
        now = datetime.datetime.now()
        remaining = target_datetime - now
        if remaining.total_seconds() <= 0:
            print(f"\n🚀 {event_name} is happening…
46 0 Open
Automation & scripting medium

Build an RSS feed from markdown blog posts in Python

Scans a folder of markdown files, extracts titles, dates, and excerpts, and generates a valid RSS 2.0 XML feed.

rss markdown xml
Python
import re
from pathlib import Path
from xml.etree.ElementTree import Element, SubElement, tostring
from datetime import datetime, timezone
from xml.dom import minidom

def build_rss(blog_dir, site_url="https://example.com"):
    feed = Element("rss", version="2.0")
    channel = SubElement(feed, "channel")
    SubElem…
11 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

Generate Holiday Calendars for Different Countries in Python

Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.

calendar datetime holidays
Python
import calendar
from datetime import date, timedelta

def generate_holiday_calendar(country_code, year=2025):
    holidays = []
    
    if country_code == "US":
        # New Year's Day
        holidays.append(date(year, 1, 1))
        # Independence Day
        holidays.append(date(year, 7, 4))
        # Thanksgivin…
40 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 easy

How to Backup an SQLite Database with a Timestamp in Python

Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.

sqlite backup automation
Python
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path

def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
    db = Path(db_path)
    backup_folder = Path(backup_dir)
    backup_folder.mkdir(exist_ok=True)
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 …
14 0 Open
Automation & scripting medium

How to Build a Mock Route53 DNS API in Python

Create a mock DNS API server in Python that simulates Route53 record lookups and updates using the standard library.

mock-server dns http-server
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs


class DNSUpdateHandler(BaseHTTPRequestHandler):
    records = {"example.com": "1.2.3.4"}

    def do_GET(self):
        domain = parse_qs(urlparse(self.path).query).get("domain", [""])[0]
        if dom…
13 0 Open
Automation & scripting easy

How to Bump Version in pyproject.toml Using Regex in Python

Updates the version field in a pyproject.toml file using a regex substitution with the Python standard library.

pyproject regex versioning
Python
import re
from pathlib import Path

def bump_version(pyproject_path: str, new_version: str) -> None:
    """Update version in pyproject.toml using regex."""
    path = Path(pyproject_path)
    content = path.read_text()

    # Match version = "x.y.z" (simple or PEP 440 with pre-release)
    pattern = r'^version\s*=\s*…
13 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 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 Find Stale GitHub Issues in Python

Filter a list of GitHub issues to find those not updated within a configurable number of days using Python datetime arithmetic.

github issues automation
Python
import os
from datetime import datetime, timezone, timedelta
import re

# Simulated GitHub issue data structure
SAMPLE_ISSUES = [
    {"number": 101, "title": "Login button not working", "updated_at": "2025-06-01T12:00:00Z", "assignee": "alice"},
    {"number": 102, "title": "Fix database migration error", "updated_at…
35 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 easy

How to Update a Hosts File to Block Distractions in Python

This script updates a local hosts file (or a demo file) by adding or updating entries to block distracting websites like Facebook and Twitter.

hosts-file automation blocking
Python
from pathlib import Path

def update_hosts(entries):
    """
    Add or update blocking entries in the hosts file.
    Uses a local demo file by default to avoid system changes.
    """
    hosts_path = Path("demo_hosts.txt")
    
    # Create demo file if it doesn't exist
    if not hosts_path.exists():
        hosts…
11 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…
45 0 Open
Automation & scripting easy

How to Write an IP Block List to hosts.deny in Python

This Python script validates a list of IP addresses and CIDR ranges, then writes them to a hosts.deny file to block connections at the TCP wrapper level.

hosts.deny ip-block ipaddress
Python
from ipaddress import ip_network

def write_hosts_deny(ip_list, output_file="hosts.deny"):
    with open(output_file, "w") as f:
        for ip in ip_list:
            try:
                ip_network(ip)
                f.write(f"ALL: {ip}\n")
            except ValueError:
                continue
    print(f"Written…
14 0 Open
Automation & scripting easy

How to validate argparse CLI commands in Python

Build a beginner-friendly command-line argument parser with argparse, including required and optional arguments, plus simple validation for age.

argparse cli validation
Python
import argparse


def main():
    parser = argparse.ArgumentParser(description="Validate CLI arguments for beginners.")
    parser.add_argument("name", type=str, help="Your name.")
    parser.add_argument("--age", type=int, default=None, help="Your age (optional).")
    parser.add_argument("--verbose", action="store_t…
13 0 Open
Automation & scripting easy

Parse WHOIS Data with Python Regex

Extract domain registration fields from a mock WHOIS record using regex and compute days until expiration.

whois regex parsing
Python
import re
from datetime import datetime


def parse_whois(whois_text: str) -> dict:
    """Extract key registration fields from a mock WHOIS record."""
    patterns = {
        "domain": r"Domain Name:\s*(.+)",
        "registrar": r"Registrar:\s*(.+)",
        "creation_date": r"Creation Date:\s*(.+)",
        "expir…
12 0 Open
Automation & scripting easy

Parse cron expression and compute next run datetime in Python

Parse a 5-field cron expression and compute the next matching datetime starting from a given base time.

cron datetime scheduling
Python
from datetime import datetime, timedelta
import re

def parse_cron_and_next_run(cron_expr, base_time=None):
    """Parse a cron expression and compute the next run time."""
    if base_time is None:
        base_time = datetime.now().replace(second=0, microsecond=0)

    fields = cron_expr.split()
    if len(fields) !…
11 0 Open
Automation & scripting easy

Resize Disk Partitions in Python (Mock Script)

A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.

disk partition dataclass
Python
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict


@dataclass
class Partition:
    name: str
    size_gb: int
    mount_point: str

    def to_dict(self) -> Dict[str, object]:
        return {
            "name": …
16 0 Open
Automation & scripting easy

Restrict Secrets File Permissions with the chmod Script in Python

This script restricts a secrets file to 0600 permissions, rotates it to a dated backup, and creates a fresh protected file for secure automation workflows.

chmod permissions secrets
Python
import os
import sys
import stat
from pathlib import Path

def restrict_secrets_file(filepath: str) -> None:
    """Set restrictive permissions (0600) on a secrets file."""
    path = Path(filepath).expanduser()
    
    if not path.is_file():
        raise FileNotFoundError(f"Secrets file not found: {path}")
    
   …
13 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.