本文目录导读:

我来帮你写一个监控文件夹空间的脚本,根据不同的需求,我提供几个版本:
Linux/Mac Bash版本
#!/bin/bash
# 文件夹空间监控脚本
# 使用方法: ./monitor_folder.sh /path/to/folder [阈值(MB)]
FOLDER="${1:-.}" # 默认当前目录
THRESHOLD="${2:-1000}" # 默认1000MB阈值
# 检查文件夹是否存在
if [ ! -d "$FOLDER" ]; then
echo "错误: 文件夹 $FOLDER 不存在"
exit 1
fi
# 获取文件夹大小(以MB为单位)
get_folder_size() {
if [[ "$OSTYPE" == "darwin"* ]]; then
# macOS
du -sm "$1" 2>/dev/null | cut -f1
else
# Linux
du -sb "$1" 2>/dev/null | awk '{printf "%.0f", $1/1048576}'
fi
}
# 获取大小
SIZE_MB=$(get_folder_size "$FOLDER")
SIZE_GB=$(echo "scale=2; $SIZE_MB / 1024" | bc)
# 输出信息
echo "文件夹: $FOLDER"
echo "当前大小: ${SIZE_MB}MB (${SIZE_GB}GB)"
echo "阈值: ${THRESHOLD}MB"
# 检查是否超过阈值
if [ "$SIZE_MB" -gt "$THRESHOLD" ]; then
echo "⚠️ 警告: 文件夹空间超过阈值!"
echo "超出: $((SIZE_MB - THRESHOLD))MB"
# 可选: 发送警报
# mail -s "文件夹空间警告" admin@example.com <<< "文件夹 $FOLDER 已使用 ${SIZE_MB}MB"
exit 1
else
echo "✅ 空间使用正常"
exit 0
fi
Windows PowerShell版本
# monitor_folder.ps1
param(
[string]$FolderPath = ".", # 默认当前目录
[int]$ThresholdMB = 1000 # 默认阈值1000MB
)
# 检查文件夹是否存在
if (-not (Test-Path $FolderPath)) {
Write-Error "文件夹 $FolderPath 不存在"
exit 1
}
# 计算文件夹大小
function Get-FolderSize {
param([string]$Path)
$size = (Get-ChildItem $Path -Recurse -Force -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum).Sum
return [math]::Round($size / 1MB, 2)
}
# 获取文件夹大小
$sizeMB = Get-FolderSize $FolderPath
$sizeGB = [math]::Round($sizeMB / 1024, 2)
# 输出信息
Write-Host "文件夹: $FolderPath"
Write-Host "当前大小: ${sizeMB}MB (${sizeGB}GB)"
Write-Host "阈值: ${ThresholdMB}MB"
# 检查是否超过阈值
if ($sizeMB -gt $ThresholdMB) {
Write-Host "⚠️ 警告: 文件夹空间超过阈值!" -ForegroundColor Red
Write-Host "超出: $($sizeMB - $ThresholdMB)MB" -ForegroundColor Red
# 可选: 发送警报
# Send-MailMessage -To "admin@example.com" -Subject "文件夹空间警告" ...
exit 1
} else {
Write-Host "✅ 空间使用正常" -ForegroundColor Green
exit 0
}
Python版本(跨平台)
#!/usr/bin/env python3
# monitor_folder.py
import os
import sys
import argparse
from pathlib import Path
def get_folder_size(folder_path):
"""计算文件夹大小"""
total_size = 0
folder = Path(folder_path)
if not folder.exists():
raise FileNotFoundError(f"文件夹 {folder_path} 不存在")
for item in folder.rglob('*'):
if item.is_file():
total_size += item.stat().st_size
return total_size # 返回字节数
def format_size(bytes_size):
"""格式化显示大小"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_size < 1024:
return f"{bytes_size:.2f} {unit}"
bytes_size /= 1024
return f"{bytes_size:.2f} PB"
def main():
parser = argparse.ArgumentParser(description='监控文件夹空间')
parser.add_argument('folder', nargs='?', default='.', help='要监控的文件夹路径')
parser.add_argument('-t', '--threshold', type=float, default=1000,
help='阈值(MB),默认1000MB')
parser.add_argument('--alert', action='store_true', help='启用警报功能')
args = parser.parse_args()
try:
size_bytes = get_folder_size(args.folder)
size_mb = size_bytes / (1024 * 1024)
threshold_bytes = args.threshold * 1024 * 1024
print(f"文件夹: {Path(args.folder).resolve()}")
print(f"当前大小: {format_size(size_bytes)} ({size_mb:.2f} MB)")
print(f"阈值: {args.threshold:.0f} MB")
if size_mb > args.threshold:
print(f"⚠️ 警告: 超过阈值 {(size_mb - args.threshold):.2f} MB")
if args.alert:
# 这里可以添加发送邮件的代码
print("警报已触发")
return 1
else:
print("✅ 空间使用正常")
return 0
except Exception as e:
print(f"错误: {e}")
return 1
if __name__ == "__main__":
sys.exit(main())
定时监控脚本(Cron配置)
Linux定时任务配置:
# 每天8点和18点检查 0 8,18 * * * /path/to/monitor_folder.sh /data/folder 5000 >> /var/log/folder_monitor.log 2>&1 # 每30分钟检查一次 */30 * * * * /path/to/monitor_folder.sh /data/folder 5000
Windows任务计划程序:
# 创建定时任务 $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-File C:\scripts\monitor_folder.ps1 -FolderPath D:\data -ThresholdMB 5000" $trigger = New-ScheduledTaskTrigger -Daily -At "08:00AM" Register-ScheduledTask -TaskName "FolderMonitor" -Action $action -Trigger $trigger
Docker版本
# Dockerfile FROM alpine:latest RUN apk add --no-cache bash COPY monitor_folder.sh /usr/local/bin/ RUN chmod +x /usr/local/bin/monitor_folder.sh CMD ["/usr/local/bin/monitor_folder.sh", "/data", "1000"]
使用示例
Linux:
# 赋予执行权限 chmod +x monitor_folder.sh # 监控/data/logs文件夹,阈值500MB ./monitor_folder.sh /data/logs 500 # 加入定时任务 crontab -e */30 * * * * /path/to/monitor_folder.sh /data/logs 1000 >> /var/log/folder_monitor.log
Windows Powershell:
# 设置执行策略 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser # 运行脚本 .\monitor_folder.ps1 -FolderPath "D:\Logs" -ThresholdMB 500
Python:
# 基本使用 python monitor_folder.py /path/to/folder # 带阈值 python monitor_folder.py /path/to/folder -t 500 # 完整参数 python monitor_folder.py /path/to/folder -t 500 --alert
扩展功能建议
如果你需要更高级的功能,可以添加:
- 邮件告警:超过阈值时自动发送邮件
- 日志记录:记录历史监控数据
- 趋势分析:查看文件夹增长趋势
- 自动清理:自动删除过期文件
- 多文件夹监控:同时监控多个目录
选择一个适合你环境的版本,根据需要进行调整。