How to Quarantine Suspicious Files in Python
Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.
Python code
41 linesimport 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)
quarantine_path.mkdir(exist_ok=True)
moved_files = []
for file_path in source_path.iterdir():
if file_path.is_file() and file_path.suffix.lower() in suspicious_extensions:
destination = quarantine_path / file_path.name
shutil.move(str(file_path), str(destination))
moved_files.append(file_path.name)
return moved_files
if __name__ == "__main__":
# Create test directories and files
test_source = "test_downloads"
test_quarantine = "test_quarantine"
os.makedirs(test_source, exist_ok=True)
# Create sample files
Path(test_source, "document.pdf").write_text("safe")
Path(test_source, "script.exe").write_text("suspicious")
Path(test_source, "setup.bat").write_text("dangerous")
Path(test_source, "image.jpg").write_text("safe")
# Quarantine suspicious files
suspicious = {".exe", ".bat", ".msi"}
moved = quarantine_files(test_source, test_quarantine, suspicious)
print(f"Quarantined {len(moved)} suspicious files: {moved}")
print(f"Remaining files: {sorted(f.name for f in Path(test_source).iterdir())}")
print(f"Quarantine contents: {sorted(f.name for f in Path(test_quarantine).iterdir())}")
Output
Quarantined 2 suspicious files: ['script.exe', 'setup.bat']
Remaining files: ['document.pdf', 'image.jpg']
Quarantine contents: ['script.exe', 'setup.bat']
How it works
The quarantine_files function walks the source directory with Path.iterdir(), checking each file's suffix against a set of suspicious extensions. Case-insensitive comparison via .lower() catches .EXE as well as .exe. quarantine_path.mkdir(exist_ok=True) creates the quarantine folder if it doesn't exist, then shutil.move relocates each suspicious file, preserving its original name. The function returns a list of moved filenames for logging or reporting, while the __main__ block demonstrates the setup and verifies the results.
Common mistakes
- Forgetting to use `.is_file()` — directories and symlinks get skipped accidentally
- Not using `.lower()` on suffixes, missing files like `.EXE`
- Hardcoding the quarantine path instead of creating it dynamically with `mkdir`
Variations
- Use `os.scandir` for a faster iterator on large directories
- Add a timestamp prefix to quarantined filenames to avoid collisions
- Log moved files to a CSV audit trail for compliance
Real-world use cases
- In an email gateway, isolate attachments with dangerous extensions (e.g., .exe, .bat) before scanning.
- In a CI pipeline, move build artifacts with suspicious extensions to a quarantine bucket for manual review.
- In a file-sharing service, quarantine uploads containing executable code to prevent malware distribution.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.