Using LLMs to Write Disk Cleanup Scripts: Safe Workflows and API Selection

    Large language models (LLMs) are excellent for quickly drafting operations scripts, but any script involving deletions requires a strict workflow: preview, quarantine, and manual confirmation. This article explores how to leverage LLMs for disk cleanup scripts, outlines a secure four-step cleanup process, addresses potential risks, and provides best practices for handling cloud API rate limiting, resuming interrupted tasks, and choosing between cloud, dedicated, and local deployments.

    The Value and Boundaries of LLM-Generated Scripts

    When troubleshooting disk space, developers often repeatedly check du and find parameters, handle insufficient permissions, and deal with exceptions like symlinks and mount points. LLMs can translate natural language requests such as “find and list old logs over 100MB” into structured code, allowing developers to focus on business logic.

    However, model-generated code is only a draft. It doesn’t know which logs on the server are currently being written, which directories contain audit data, or the team’s backup strategy. Scripts involving deletion, overwriting, or permission changes must undergo human review and be validated in a test environment before deployment.

    The Four-Step Disk Cleanup Process

    Consider a server where a 1TB disk is full. Record the used and available space with df before and after cleanup to show the actual space freed.

    Step 1: Analyze Space Usage

    1. df -h /
    2. sudo du -xh --max-depth=1 /var 2>/dev/null | sort -h | tail -n 20

    The -x parameter of du limits statistics to the same file system, preventing data from other mounted disks from mixing into the results. Scanning the root directory directly on a large disk can take several minutes. It is recommended to start from suspected large directories like /var or /data and drill down layer by layer.

    The statistics from du may not match the usage shown by df. There are two common reasons. First, processes may still hold deleted files open, which can be checked using sudo lsof +L1. Second, the file system reserves space for the root user. Do not rush to delete files before identifying the cause.

    Step 2: Preview

    The script below defaults to generating only a CSV report without moving any files. Running with root privileges is recommended because lsof needs to read the file tables of other users’ processes.

    1. #!/usr/bin/env python3
    2. """Disk cleanup script. Generates only a preview report by default; with --execute, only quarantines files marked as 'Delete' in the report."""
    3. import argparse
    4. import csv
    5. import os
    6. import shutil
    7. import stat
    8. import subprocess
    9. import sys
    10. import time
    11. MB = 1024 * 1024
    12. # Add or remove based on actual server conditions; better to over-protect than miss
    13. PROTECTED_PATHS = ("/etc", "/boot", "/usr", "/bin", "/sbin", "/lib", "/lib64",
    14. "/var/lib", "/proc", "/sys", "/dev", "/run")
    15. REPORT_FIELDS = ["path", "size_mb", "mtime", "age_days", "inode", "nlink", "reviewer_decision"]
    16. LOG_FIELDS = ["src", "dest", "size_bytes", "time"]
    17. DELETE_MARK = "Delete"
    18. def is_under(path, base):
    19. return path == base or path.startswith(base.rstrip(os.sep) + os.sep)
    20. def is_protected(path):
    21. real = os.path.realpath(path)
    22. return any(is_under(real, p) for p in PROTECTED_PATHS)
    23. def is_open_by_process(path):
    24. """Returns True if a process has the file open, False if confirmed not. Raises RuntimeError if undetermined."""
    25. r = subprocess.run(["lsof", "-t", "--", path],
    26. stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    27. if r.returncode == 0:
    28. return True
    29. # Return code 1 with no error output means no process has it open.
    30. # If permissions are insufficient, lsof outputs a warning to stderr. Treat as "undetermined", not as unopened.
    31. if r.returncode == 1 and not r.stderr.strip():
    32. return False
    33. raise RuntimeError(f"Unable to determine open status: {path}; lsof output: {r.stderr.strip()}")
    34. def scan(root, min_mb, min_age_days, exts):
    35. now = time.time()
    36. root_dev = os.lstat(root).st_dev
    37. results = []
    38. for dirpath, _, filenames in os.walk(root, followlinks=False):
    39. for name in filenames:
    40. if not name.lower().endswith(exts): # Case-insensitive extension matching
    41. continue
    42. fp = os.path.join(dirpath, name)
    43. try:
    44. st = os.lstat(fp)
    45. except OSError:
    46. continue
    47. # Skip symlinks, special files, and other file systems mounted on subdirectories
    48. if not stat.S_ISREG(st.st_mode) or st.st_dev != root_dev:
    49. continue
    50. age_days = (now - st.st_mtime) / 86400
    51. if st.st_size < min_mb * MB or age_days < min_age_days:
    52. continue
    53. results.append({
    54. "path": fp,
    55. "size": st.st_size,
    56. "age": age_days,
    57. "mtime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime)),
    58. "inode": st.st_ino,
    59. "nlink": st.st_nlink,
    60. })
    61. results.sort(key=lambda x: x["size"], reverse=True)
    62. return results
    63. def write_report(items, report_path):
    64. kept = 0
    65. with open(report_path, "w", newline="", encoding="utf-8") as f:
    66. writer = csv.DictWriter(f, fieldnames=REPORT_FIELDS)
    67. writer.writeheader()
    68. for c in items:
    69. if is_protected(c["path"]):
    70. continue
    71. if c["nlink"] > 1: # Hard links: deleting one name doesn't free space; the other name may still be in use
    72. continue
    73. try:
    74. if is_open_by_process(c["path"]):
    75. continue
    76. except RuntimeError as e:
    77. print(f"[Skip] {e}")
    78. continue
    79. writer.writerow({
    80. "path": c["path"],
    81. "size_mb": round(c["size"] / MB, 2),
    82. "mtime": c["mtime"],
    83. "age_days": round(c["age"], 1),
    84. "inode": c["inode"],
    85. "nlink": c["nlink"],
    86. "reviewer_decision": "", # Filled by human: Delete or Keep
    87. })
    88. kept += 1
    89. return kept
    90. def quarantine(rows, root, qdir, log_path):
    91. qdev = os.stat(qdir).st_dev
    92. freed = 0
    93. new_log = not os.path.exists(log_path)
    94. with open(log_path, "a", newline="", encoding="utf-8") as lf:
    95. log = csv.writer(lf)
    96. if new_log:
    97. log.writerow(LOG_FIELDS)
    98. for row in rows:
    99. src = os.path.normpath(row["path"]) # Report is edited by humans, treat as untrusted input
    100. dest = os.path.join(qdir, os.path.relpath(src, root))
    101. reason = None
    102. try:
    103. st = os.lstat(src)
    104. except OSError as e:
    105. reason = f"Cannot read: {e}"
    106. else:
    107. if not is_under(src, root):
    108. reason = "Path not in scan root directory"
    109. elif not stat.S_ISREG(st.st_mode):
    110. reason = "Not a regular file"
    111. elif st.st_nlink > 1:
    112. reason = "Hard link"
    113. elif st.st_dev != qdev:
    114. reason = "Not on the same file system as the quarantine directory"
    115. elif is_protected(src):
    116. reason = "Protected path"
    117. elif os.path.exists(dest):
    118. reason = "Destination already exists, do not overwrite"
    119. else:
    120. try:
    121. if is_open_by_process(src):
    122. reason = "File is currently open by a process"
    123. except RuntimeError as e:
    124. reason = str(e)
    125. if reason:
    126. print(f"[Skip] {src}: {reason}")
    127. continue
    128. os.makedirs(os.path.dirname(dest), exist_ok=True)
    129. os.rename(src, dest) # Same file system move is atomic, does not copy then delete
    130. log.writerow([src, dest, st.st_size, time.strftime("%Y-%m-%d %H:%M:%S")])
    131. lf.flush()
    132. os.fsync(lf.fileno()) # Each record is flushed to disk; allows rollback if interrupted midway
    133. freed += st.st_size
    134. print(f"[Quarantined] {src} -> {dest}")
    135. return freed
    136. def main():
    137. ap = argparse.ArgumentParser(description="Disk cleanup: generates only a preview report by default")
    138. ap.add_argument("--root", required=True, help="Scan root directory, e.g., /var")
    139. ap.add_argument("--report", default="cleanup_report.csv", help="Preview report path")
    140. ap.add_argument("--min-mb", type=int, default=100, help="Minimum file size (MB)")
    141. ap.add_argument("--min-age-days", type=float, default=30, help="Minimum days since last modification")
    142. ap.add_argument("--ext", default=".log,.gz,.tmp,.bak,.old", help="Extensions, comma-separated")
    143. ap.add_argument("--execute", action="store_true", help="Quarantine files marked for deletion in the report")
    144. ap.add_argument("--qdir", help="Quarantine directory, must be pre-created and on the same file system as root")
    145. ap.add_argument("--log", default="quarantine_log.csv", help="Quarantine operation log")
    146. args = ap.parse_args()
    147. if shutil.which("lsof") is None:
    148. sys.exit("lsof not found, cannot check file open status, script stopped")
    149. if os.geteuid() != 0:
    150. print("[Notice] Non-root run, cannot read open files of other users' processes; some files will be skipped due to undetermined status")
    151. root = os.path.realpath(args.root)
    152. exts = tuple(e.strip().lower() for e in args.ext.split(",") if e.strip())
    153. if not args.execute:
    154. items = scan(root, args.min_mb, args.min_age_days, exts)
    155. kept = write_report(items, args.report)
    156. print(f"Scanned {len(items)} candidate files, wrote {kept} preview entries: {args.report}")
    157. print("Please fill in Delete or Keep in the reviewer_decision column, then rerun with --execute.")
    158. return
    159. if not args.qdir or not os.path.isdir(args.qdir):
    160. sys.exit("Execution of quarantine requires --qdir, and the directory must already exist")
    161. qdir = os.path.realpath(args.qdir)
    162. with open(args.report, newline="", encoding="utf-8") as f:
    163. rows = [r for r in csv.DictReader(f) if r["reviewer_decision"].strip() == DELETE_MARK]
    164. if not rows:
    165. sys.exit("No records marked as Delete in the report, no operations performed")
    166. print(f"To quarantine {len(rows)} files, quarantine directory: {qdir}")
    167. if input("Enter YES to confirm quarantine (any other input cancels): ").strip() != "YES":
    168. sys.exit("Cancelled")
    169. freed = quarantine(rows, root, qdir, args.log)
    170. print(f"Quarantine complete, total {freed / MB:.1f} MB. Space will only be truly freed after the quarantine directory is emptied.")
    171. if __name__ == "__main__":
    172. main()

    Step 3: Quarantine

    Quarantine is not deletion. The script uses os.rename to move files into a quarantine directory, preserving the original relative path structure for easy recovery later. The quarantine directory must be on the same file system as the directory being cleaned. Otherwise, rename will fail, or shutil.move will degrade to “copy and delete”. If power is lost while copying a multi-gigabyte log, a partial file may remain while the original could have been deleted. The script checks this before execution.

    After quarantine, space is not immediately freed because the files still occupy the same disk. The space returns to the file system only after the quarantine directory is emptied. This is the purpose of quarantine: if a misjudgment is discovered during the observation period, files can be moved back without permanent loss.

    Step 4: Confirmation

    Manual confirmation involves two gates. The first is the preview report. The reviewer fills in “Delete” or “Keep” for each entry in the reviewer_decision column; unfamiliar paths are always marked “Keep”. The second is the interactive confirmation during execution. The script only moves files after receiving “YES” as input; any other input cancels the operation.

    Every execution must leave a record. The quarantine log quarantine_log.csv records the source path, destination path, size, and time. It is recommended to archive the preview report, quarantine log, and approver’s name together, and agree on a retention period for the quarantine directory, such as deleting it permanently after a 7-day observation with a second person’s approval.

    Risks to Check Before Running

    First, lsof permissions. When run by a non-root user, lsof cannot see other users’ processes, making it impossible to confirm whether a file is still open. In this case, lsof may only output a warning to stderr with a return code of 1. If return code 1 is directly treated as “not open”, the script might move a log being actively written. Therefore, the script only considers the file as not open when the return code is 1 and there is no error output; it skips all other cases.

    Second, hard links. When an inode has multiple filenames, deleting one name does not free space. The script skips these files via st_nlink.

    Third, symlinks and mount points. os.walk sets followlinks=False, so it will not enter directories pointed to by symlinks. The script also compares the st_dev of each file with the device number of the scan root directory, preventing disks mounted in subdirectories from being processed incorrectly.

    Fourth, the time window. Between preview and execution, a file might be opened by a new process. The script checks again before execution, but there is still a minimal gap between the check and the move. This window cannot be completely eliminated, so cleanup tasks are best run during low-load periods, with the quarantine directory as a fallback.

    Fifth, protected paths. Directories in PROTECTED_PATHS will not be moved even if mistakenly marked as “Delete”. This list should be maintained according to the actual server conditions; it is better to over-protect than to miss a critical path.

    Handling Rate Limits and Disconnections with Cloud APIs

    When calling cloud models, there are three common types of failures. First, returning 429, indicating rate limiting. Second, returning 5xx, indicating temporary server unavailability. Third, network connection failures or timeouts. These three errors are usually retryable. Other 4xx errors, such as parameter errors or authentication failures, do not benefit from retrying and should raise an error directly.

    Retries should follow three rules. First, if there is a Retry-After response header, prioritize waiting accordingly. Second, use exponential backoff with random jitter to prevent multiple tasks from retrying simultaneously and causing a spike. Third, set a maximum retry count and timeout to expose failures early. Here is a set of parameters to start with: connection timeout 10 seconds, read timeout 120 seconds, maximum 4 retries, and a maximum single wait of 60 seconds. These values need to be adjusted based on actual response times and the provider’s rate limiting policy.

    1. import os
    2. import random
    3. import time
    4. import requests
    5. API_URL = os.environ["LLM_API_URL"]
    6. API_KEY = os.environ["LLM_API_KEY"] # Key is only read from environment variables, not written in code or logs
    7. HEADERS = {"Authorization": f"Bearer {API_KEY}"}
    8. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    9. def call_llm(prompt, max_retries=4):
    10. for attempt in range(max_retries + 1):
    11. try:
    12. resp = requests.post(API_URL, headers=HEADERS,
    13. json={"prompt": prompt}, timeout=(10, 120))
    14. except (requests.ConnectionError, requests.Timeout):
    15. resp = None # Network layer failure, enter retry branch
    16. if resp is not None and resp.status_code not in RETRYABLE_STATUS:
    17. resp.raise_for_status() # Non-retryable errors are raised directly, e.g., 400 or 401
    18. return resp.json()
    19. if attempt == max_retries:
    20. raise RuntimeError("Max retries exhausted, please check service status or quota")
    21. delay = min(60, 2 ** attempt) + random.uniform(0, 1)
    22. time.sleep(delay)

    Note that retries only apply to calls without side effects, such as “generating text”. If the model call triggers a deletion, sends a message, or deducts funds, blind retries may cause duplicate operations. Such calls should use an idempotency key or query whether the result has already been generated before execution.

    Resuming Interrupted Tasks

    Cleanup script prompts often need to process hundreds or thousands of directories. A single task may run for hours, and failing midway due to rate limiting or network fluctuations is common. The approach for resuming is to split the task into independent small units, such as one unit per directory, and write the result to a state file upon completing each unit. Upon restart, the script reads the state file and skips completed units.

    1. import json
    2. import os
    3. STATE_FILE = "gen_state.json"
    4. def load_state():
    5. if os.path.exists(STATE_FILE):
    6. with open(STATE_FILE, encoding="utf-8") as f:
    7. return json.load(f)
    8. return {}
    9. def save_state(state):
    10. tmp = STATE_FILE + ".tmp"
    11. with open(tmp, "w", encoding="utf-8") as f:
    12. json.dump(state, f, ensure_ascii=False)
    13. f.flush()
    14. os.fsync(f.fileno())
    15. os.replace(tmp, STATE_FILE) # Write to temp file then atomically replace; power loss won't corrupt the state file
    16. def run_tasks(tasks, call_fn):
    17. """tasks is a dict of {unit_name: prompt}, call_fn is the call_llm above."""
    18. state = load_state()
    19. for name, prompt in tasks.items():
    20. if name in state:
    21. continue # Completed units are skipped directly
    22. state[name] = call_fn(prompt)
    23. save_state(state)
    24. return state

    The resumed results must be validated. Model outputs are random; the same prompt may yield different results on two runs. For script-like outputs, check the syntax first using python -m py_compile before human review. The state file should only save results that have passed review; unreviewed content should not enter the execution phase.

    Choosing Between Cloud, Dedicated, and Local Deployment

    There is no universal answer; it depends on data sensitivity, stability requirements, and the team’s operational capabilities. The table below compares the three methods across several dimensions.

    Dimension Cloud API Dedicated Deployment Local Deployment
    Startup Cost Low, pay-as-you-go Medium, requires contract and resource reservation High, requires hardware purchase
    Data Destination Data passes through provider Data processed in a dedicated environment Data stays in the internal network
    Stability Affected by provider rate limits and queuing Exclusive resources, less fluctuation Depends on your own ops capability
    Model Version Provider decides when to upgrade Version can be agreed upon Upgraded by the team
    Ops Personnel Low Medium High

    When selecting, check in the following order:

    1. First, confirm whether data is allowed to leave the internal network. Content involving user privacy, audit data, or contractual constraints should prioritize dedicated or local deployment.
    2. Estimate call volume and peak loads. If there are only a few dozen calls per day on average, the cloud API is the most cost-effective. If rate limits are frequently triggered during peak hours, evaluate dedicated deployment.
    3. Assess whether the team can maintain GPU servers, inference frameworks, and model updates. Without the necessary personnel, the hidden costs of local deployment are high.
    4. Regardless of the chosen method, retain retry, checkpointing, and output validation. These mechanisms do not need to be rewritten when the deployment form changes.

    Implementation Recommendations

    It is recommended to start with the cloud API, run the three steps of preview, quarantine, and confirmation on a test machine, and then gradually open it to the production environment. Prompts and script templates should be version-controlled, and the model version, parameters, and time of each call should be recorded for traceability. Deletion permissions should only be granted to the account responsible for cleanup; the model generating the script or standard developer accounts should not directly possess root deletion capabilities.

    LLMs can significantly reduce the time spent writing scripts, but the responsibility for deleting data remains with humans. The four gates—preview, quarantine, confirmation, and audit records—are indispensable.