Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Find Sensitive Information in Log Files with Python
Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in 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'…
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
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.
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-…
How to Detect Recently Installed Software in Python
Uses subprocess to call pip and parse package metadata to list recently installed Python packages.
import subprocess
import sys
from datetime import datetime, timedelta
def detect_recently_installed(days=7):
"""Detect recently installed software packages."""
recent_packages = []
cutoff_date = datetime.now() - timedelta(days=days)
try:
# For pip-installed packages (Python packages)
…
How to Quarantine Suspicious Files in Python
Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.
import shutil
import os
from pathlib import Path
def quarantine_files(source_dir, quarantine_dir, suspicious_extensions):
"""
Move files with suspicious extensions to a quarantine folder.
Returns list of moved files.
"""
source_path = Path(source_dir)
quarantine_path = Path(quarantine_dir)
…
How to Scan Configuration Files for Security Issues in Python
Automatically scan configuration files for common security mistakes using regex rules in Python.
import re
import os
from pathlib import Path
SECURITY_RULES = [
(r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
(r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
(r'debug\s*=\s*True', 'Debug mode enabled'),
(r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
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.
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…
How to Scan Open Ports on a Host with Python
A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.
import socket
def scan_ports(host, start_port, end_port):
open_ports = []
for port in range(start_port, end_port + 1):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.5)
result = sock.connect_ex((host, port))
if result == 0:
open_ports.app…
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.
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…
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.
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}")
…
Rotate API keys in Python by updating an .env template
Replace an old API key with a new one inside an .env template file, with a guard for missing keys.
import json
from pathlib import Path
def rotate_api_keys(env_template_path: Path, old_key: str, new_key: str) -> None:
"""Replace an old API key with a new one in an .env template file."""
content = env_template_path.read_text()
if old_key not in content:
print(f"Error: '{old_key}' not found in {e…
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.