Add remote Docker cleanup script

This commit is contained in:
WickedYoda committed 2026-02-20 20:24:01 -06:00
1 parent 79c99d6d96
commit 47b0474f38
4 files changed
+268

No files matched your search

+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Run Docker cleanup commands on remote hosts listed in a text file."""
from __future__ import annotations
import argparse
import getpass
from datetime import datetime
from pathlib import Path
from typing import List
try:
import paramiko
except ImportError: # pragma: no cover - runtime environment dependent
paramiko = None
DOCKER_COMMANDS = [
"docker container prune -f",
"docker image prune -a -f",
"docker volume prune -f",
"docker network prune -f",
]
def parse_args() -> argparse.Namespace:
script_dir = Path(__file__).resolve().parent
parser = argparse.ArgumentParser(
description=(
"Clean up Docker containers, images, volumes, and networks "
"on all hosts listed in a text file."
)
)
parser.add_argument(
"machine_file",
nargs="?",
default=str(script_dir / "machines.txt"),
help="Path to host list file (default: docker/machines.txt).",
)
parser.add_argument(
"--timeout",
type=int,
default=20,
help="SSH connection timeout in seconds (default: 20).",
)
return parser.parse_args()
def load_hosts(machine_file: Path) -> List[str]:
hosts: List[str] = []
for raw_line in machine_file.read_text(encoding="utf-8").splitlines():
line = raw_line.split("#", 1)[0].strip()
if line:
hosts.append(line)
return hosts
def run_remote_cleanup(
host: str, username: str, password: str, timeout: int, log_handle
) -> bool:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=host,
username=username,
password=password,
timeout=timeout,
auth_timeout=timeout,
banner_timeout=timeout,
look_for_keys=False,
allow_agent=False,
)
for cmd in DOCKER_COMMANDS:
stdin, stdout, stderr = client.exec_command(cmd, timeout=300)
_ = stdin
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
code = stdout.channel.recv_exit_status()
log_handle.write(f"$ {cmd}\n")
if out:
log_handle.write(out)
if not out.endswith("\n"):
log_handle.write("\n")
if err:
log_handle.write(err)
if not err.endswith("\n"):
log_handle.write("\n")
if code != 0:
log_handle.write(f"Command failed with exit code {code}\n")
return False
return True
except Exception as exc: # pylint: disable=broad-except
log_handle.write(f"Connection or execution error: {exc}\n")
return False
finally:
client.close()
def main() -> int:
args = parse_args()
if paramiko is None:
print("Missing dependency: paramiko")
print("Install it with: python -m pip install paramiko")
return 1
machine_file = Path(args.machine_file).expanduser().resolve()
if not machine_file.exists():
print(f"Machine list file not found: {machine_file}")
return 1
hosts = load_hosts(machine_file)
if not hosts:
print(f"No hosts found in: {machine_file}")
print("Add one hostname or IP per line.")
return 1
username = input("SSH username (same account for all machines): ").strip()
if not username:
print("Username cannot be empty.")
return 1
password = getpass.getpass("SSH password: ").strip()
if not password:
print("Password cannot be empty.")
return 1
print(
"This will remove unused Docker containers, images, volumes, and "
"networks on all listed hosts."
)
confirm = input("Continue? (y/N): ").strip().lower()
if confirm != "y":
print("Cancelled.")
return 0
log_name = f"docker_cleanup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
log_path = Path(__file__).resolve().parent / log_name
success = 0
failed = 0
with log_path.open("w", encoding="utf-8") as log_handle:
log_handle.write(f"Docker cleanup run started: {datetime.now()}\n")
log_handle.write(f"Machine file: {machine_file}\n\n")
for host in hosts:
print(f"Running cleanup on {host} ...")
log_handle.write(f"========== {host} ==========\n")
ok = run_remote_cleanup(
host=host,
username=username,
password=password,
timeout=args.timeout,
log_handle=log_handle,
)
if ok:
success += 1
print(f"SUCCESS: {host}")
log_handle.write(f"SUCCESS: {host}\n\n")
else:
failed += 1
print(f"FAILED: {host}")
log_handle.write(f"FAILED: {host}\n\n")
print(f"Run complete. Successful hosts: {success}, Failed hosts: {failed}")
print(f"Log file: {log_path}")
return 0 if failed == 0 else 2
if __name__ == "__main__":
raise SystemExit(main())
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env bash
set -u
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MACHINE_FILE="${1:-$SCRIPT_DIR/machines.txt}"
LOG_FILE="$SCRIPT_DIR/docker_cleanup_$(date +%Y%m%d_%H%M%S).log"
if [[ ! -f "$MACHINE_FILE" ]]; then
echo "Machine list file not found: $MACHINE_FILE"
echo "Create it with one hostname or IP per line."
exit 1
fi
if ! command -v sshpass >/dev/null 2>&1; then
echo "sshpass is required but not installed."
echo "Install it and run the script again."
exit 1
fi
read -r -p "SSH username (same account for all machines): " SSH_USER
if [[ -z "$SSH_USER" ]]; then
echo "Username cannot be empty."
exit 1
fi
read -r -s -p "SSH password: " SSH_PASS
echo
if [[ -z "$SSH_PASS" ]]; then
echo "Password cannot be empty."
exit 1
fi
trap 'unset SSH_PASS' EXIT
echo "This will remove unused Docker containers, images, volumes, and networks on all listed hosts."
read -r -p "Continue? (y/N): " CONFIRM
if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
echo "Cancelled."
exit 0
fi
echo "Docker cleanup run started: $(date)" | tee "$LOG_FILE"
echo "Machine file: $MACHINE_FILE" | tee -a "$LOG_FILE"
echo | tee -a "$LOG_FILE"
SUCCESS_COUNT=0
FAIL_COUNT=0
while IFS= read -r RAW_LINE || [[ -n "$RAW_LINE" ]]; do
HOST="$(printf '%s' "$RAW_LINE" | sed 's/#.*$//' | xargs)"
if [[ -z "$HOST" ]]; then
continue
fi
echo "========== $HOST ==========" | tee -a "$LOG_FILE"
if sshpass -p "$SSH_PASS" ssh \
-o StrictHostKeyChecking=no \
-o UserKnownHostsFile=/dev/null \
-o ConnectTimeout=12 \
"$SSH_USER@$HOST" 'bash -s' >>"$LOG_FILE" 2>&1 <<'REMOTE_CLEANUP'
set -e
docker container prune -f
docker image prune -a -f
docker volume prune -f
docker network prune -f
REMOTE_CLEANUP
then
echo "SUCCESS: $HOST" | tee -a "$LOG_FILE"
SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
else
echo "FAILED: $HOST" | tee -a "$LOG_FILE"
FAIL_COUNT=$((FAIL_COUNT + 1))
fi
echo | tee -a "$LOG_FILE"
done < "$MACHINE_FILE"
echo "Run complete: $(date)" | tee -a "$LOG_FILE"
echo "Successful hosts: $SUCCESS_COUNT" | tee -a "$LOG_FILE"
echo "Failed hosts: $FAIL_COUNT" | tee -a "$LOG_FILE"
echo "Log file: $LOG_FILE"
+5
View File
@@ -0,0 +1,5 @@
# One hostname or IP per line.
# Lines starting with # are ignored.
# Example:
# docker-host-01
# 192.168.1.20