Script to delete files from a Linux directory



Python Script to delete files from a Linux directory and send email on the status of deletion. This runs foreground and not a background script and wait till command comes out. 

import subprocess
import smtplib
from email.mime.text import MIMEText

# === CONFIG ===
DELETE_CMD = "find /your/target/folder -maxdepth 1 -type f -mtime +150 -print0 | xargs -0 -n 1000 -P 10 rm -f"
SMTP_SERVER = "smtp.gmail.com"
SMTP_PORT = 587
FROM_EMAIL = "your_email@gmail.com"
FROM_PASSWORD = "your_app_password" # Use an app-specific password
TO_EMAIL = "recipient@example.com"
SUBJECT = "File Deletion Status Report"

# === Step 1: Run the deletion command and capture output ===
try:
result = subprocess.run(DELETE_CMD, shell=True, check=True, capture_output=True, text=True)
body = f" File deletion completed successfully.\n\nSTDOUT:\n{result.stdout or 'None'}"
except subprocess.CalledProcessError as e:
body = f" File deletion failed.\n\nReturn Code: {e.returncode}\nSTDERR:\n{e.stderr or 'None'}"

# === Step 2: Send email ===
msg = MIMEText(body)
msg["Subject"] = SUBJECT
msg["From"] = FROM_EMAIL
msg["To"] = TO_EMAIL

try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(FROM_EMAIL, FROM_PASSWORD)
server.send_message(msg)
print(" Status email sent.")
except Exception as e:
print(f" Failed to send email: {e}")




Comments