Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
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.
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,
…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
How to Decrypt a GPG File with a Passphrase in Python
Decrypt a GPG-encrypted file using a passphrase via the gpg CLI wrapped in a reusable Python function.
import subprocess
import tempfile
from pathlib import Path
def decrypt_gpg_file(input_file: str, passphrase: str) -> str:
"""Decrypt a GPG file using a passphrase and return the plaintext."""
result = subprocess.run(
["gpg", "--batch", "--yes", "--passphrase", passphrase, "--decrypt", input_file],
…
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 Generate an Inventory CSV of Installed pip Packages in Python
This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.
import subprocess
import csv
def get_installed_packages():
"""Return a list of (name, version) tuples for installed pip packages."""
result = subprocess.run(
["pip", "list", "--format=freeze"],
capture_output=True,
text=True,
check=True
)
packages = []
for line in r…
How to Kill Zombie Processes Matching a Name in Python
Scans running processes with ps, finds zombies whose command name matches a pattern, and attempts to kill them with SIGKILL.
import subprocess
import re
import signal
def find_zombies(name_pattern):
"""Find PIDs of zombie processes matching the given pattern."""
result = subprocess.run(["ps", "-eo", "pid,stat,comm"], capture_output=True, text=True)
zombies = []
for line in result.stdout.splitlines()[1:]: # Skip header
…
How to Mock FFmpeg subprocess Calls in Python
Compress a video with ffmpeg while mocking subprocess.run to test the command construction without executing the actual encoder.
import subprocess
from unittest.mock import Mock, patch
def compress_video(input_path: str, output_path: str, crf: int = 23) -> None:
"""Compress a video using ffmpeg with a given CRF (quality) value."""
command = [
"ffmpeg",
"-i", input_path,
"-c:v", "libx264",
"-crf", str(cr…
How to Mock subprocess Calls in Python with unittest.mock
A Python script that wraps Vagrant up/destroy commands using subprocess, with tests that mock the subprocess call to simulate outputs and errors.
import subprocess
from unittest.mock import patch, Mock
def run_vagrant(action: str) -> str:
result = subprocess.run(
["vagrant", action],
capture_output=True,
text=True,
check=False,
)
return result.stdout.strip()
def vagrant_wrapper(action: str) -> str:
if action n…
How to Monitor USB Device Connections in Python
A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.
import time
import subprocess
import os
def get_usb_devices():
"""Return list of currently connected USB devices (Linux)."""
try:
result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
return result.stdout.strip().split('\n')
except (subprocess.CalledProcessError, F…
How to Ping Multiple Hosts in Parallel with Python ThreadPoolExecutor
A parallel host-pinging script using ThreadPoolExecutor and subprocess to check connectivity across multiple addresses concurrently.
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
HOSTS = [
"google.com",
"github.com",
"stackoverflow.com",
"nonexistent.invalid",
"localhost",
]
def ping_host(host: str) -> str:
"""Ping a single host and return a status string."""
result = subp…
How to Run Tesseract OCR from Python with subprocess
This script uses Python's subprocess module to invoke the Tesseract OCR engine from the command line and return the extracted text.
import subprocess
def ocr_image(image_path):
command = ["tesseract", image_path, "stdout"]
result = subprocess.run(command, capture_output=True, text=True)
return result.stdout.strip()
if __name__ == "__main__":
# Stub: call the actual tesseract (must be installed)
text = ocr_image("sample.png")
…
How to stage and commit all changes with Git in Python
Run git add -A and git commit from Python using subprocess to automate staging and committing all file changes in one step.
import subprocess
from pathlib import Path
def stage_and_commit_all(commit_message: str) -> None:
"""Stage all changes and create a commit with the given message."""
repo_root = Path.cwd()
if not (repo_root / ".git").exists():
raise RuntimeError("Not inside a Git repository")
subprocess.run([…
Run pytest and email summary in Python
Runs pytest via subprocess, extracts the test summary line, and sends it in an email (mocked for demonstration).
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def run_tests():
"""Run pytest and capture the summary output."""
result = subprocess.run(
["pytest", "-q"],
capture_output=True,
text=True
)
return result.stdo…
Track Internet Connectivity and Downtime Automatically in Python
Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.
import time
import subprocess
from datetime import datetime
def check_internet(host="8.8.8.8", timeout=3):
"""Returns True if internet is reachable via ping."""
try:
subprocess.run(
["ping", "-c", "1", "-W", str(timeout), host],
capture_output=True,
timeout=timeout …
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.