如何用脚本生成文件系统报告

wen 实用脚本 1

本文目录导读:

如何用脚本生成文件系统报告

  1. Linux 环境
  2. Windows 环境
  3. 定时执行报告
  4. 推荐使用方案

要用脚本生成文件系统报告,主要取决于你的操作系统和具体需求,以下是几种常见的方法,涵盖Linux和Windows环境。

Linux 环境

基础磁盘使用报告(Shell脚本)

#!/bin/bash
# 文件系统使用报告
echo "=========================================="
echo "文件系统使用报告 - $(date)"
echo "=========================================="
echo ""
# 1. 磁盘分区使用情况
echo "--- 磁盘分区使用情况 ---"
df -h
echo ""
# 2. inode使用情况
echo "--- Inode使用情况 ---"
df -i
echo ""
# 3. 磁盘整体使用情况
echo "--- 磁盘使用统计 ---"
df -h --total | grep total
echo ""
# 4. 找出占用空间最大的目录(从根目录开始,5层深)
echo "--- 占用空间最大的前10个目录 ---"
du -h / 2>/dev/null | sort -rh | head -10
echo ""
# 5. 文件系统类型信息
echo "--- 文件系统类型 ---"
df -T
echo ""
# 6. 磁盘I/O统计(需要sysstat包)
if command -v iostat &> /dev/null; then
    echo "--- 磁盘I/O统计 ---"
    iostat -x 1 2
fi

保存为 filesystem_report.sh 并执行:

chmod +x filesystem_report.sh
./filesystem_report.sh > report.txt

使用Python生成更详细的报告

#!/usr/bin/env python3
import os
import subprocess
import json
from datetime import datetime
def get_filesystem_info():
    """获取文件系统信息"""
    info = {
        "timestamp": datetime.now().isoformat(),
        "hostname": os.uname().nodename,
        "filesystems": []
    }
    # 执行df命令获取信息
    result = subprocess.run(['df', '-h', '-T'], capture_output=True, text=True)
    lines = result.stdout.strip().split('\n')[1:]  # 跳过标题行
    for line in lines:
        parts = line.split()
        if len(parts) >= 7:
            fs_info = {
                "filesystem": parts[0],
                "type": parts[1],
                "size": parts[2],
                "used": parts[3],
                "avail": parts[4],
                "use_percent": parts[5],
                "mounted_on": parts[6]
            }
            info["filesystems"].append(fs_info)
    return info
def generate_report():
    """生成报告"""
    info = get_filesystem_info()
    print("=" * 60)
    print(f"文件系统报告 - {info['hostname']}")
    print(f"生成时间: {info['timestamp']}")
    print("=" * 60)
    # 统计信息
    total_size = 0
    total_used = 0
    warning_fs = []
    print(f"\n{'文件系统':<20} {'类型':<10} {'大小':<10} {'已用':<10} {'可用':<10} {'使用率':<8} {'挂载点'}")
    print("-" * 80)
    for fs in info['filesystems']:
        print(f"{fs['filesystem']:<20} {fs['type']:<10} {fs['size']:<10} "
              f"{fs['used']:<10} {fs['avail']:<10} {fs['use_percent']:<8} {fs['mounted_on']}")
        # 检查使用率是否超过80%
        try:
            use_pct = int(fs['use_percent'].rstrip('%'))
            if use_pct > 80:
                warning_fs.append(fs['filesystem'])
        except ValueError:
            pass
    # 警告信息
    if warning_fs:
        print(f"\n{'=' * 60}")
        print("⚠️  警告:以下文件系统使用率超过80%:")
        for fs in warning_fs:
            print(f"  - {fs}")
    return info
if __name__ == "__main__":
    info = generate_report()
    # 可选择保存为JSON格式
    with open('filesystem_report.json', 'w') as f:
        json.dump(info, f, indent=2)

高级报告:包含分区和inode信息

#!/bin/bash
# 高级文件系统报告
OUTPUT_FILE="filesystem_report_$(date +%Y%m%d_%H%M%S).html"
cat > $OUTPUT_FILE << EOF
<!DOCTYPE html>
<html>
<head>文件系统报告 - $(date)</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        h1 { color: #333; }
        table { border-collapse: collapse; width: 100%; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #4CAF50; color: white; }
        tr:nth-child(even) { background-color: #f2f2f2; }
        .warning { color: red; font-weight: bold; }
        .ok { color: green; }
    </style>
</head>
<body>
    <h1>文件系统使用报告</h1>
    <p>生成时间: $(date)</p>
    <p>主机名: $(hostname)</p>
EOF
# 添加磁盘使用表格
echo "<h2>磁盘分区使用情况</h2>" >> $OUTPUT_FILE
echo "<table><tr><th>文件系统</th><th>大小</th><th>已用</th><th>可用</th><th>使用率</th><th>挂载点</th></tr>" >> $OUTPUT_FILE
df -h | tail -n +2 | while read line; do
    echo "<tr>" >> $OUTPUT_FILE
    for item in $line; do
        echo "<td>$item</td>" >> $OUTPUT_FILE
    done
    echo "</tr>" >> $OUTPUT_FILE
done
echo "</table>" >> $OUTPUT_FILE
# 添加警告信息
echo "<h2>警告信息</h2>" >> $OUTPUT_FILE
echo "<ul>" >> $OUTPUT_FILE
df -h | tail -n +2 | while read fs size used avail use mounted; do
    use_pct=${use%\%}
    if [ "$use_pct" -gt 80 ] 2>/dev/null; then
        echo "<li class='warning'>⚠️ $mounted 使用率: $use (已用: $used / 总计: $size)</li>" >> $OUTPUT_FILE
    fi
done
echo "</ul>" >> $OUTPUT_FILE
echo "</body></html>" >> $OUTPUT_FILE
echo "HTML报告已生成: $OUTPUT_FILE"

Windows 环境

PowerShell脚本

# filesystem_report.ps1
Write-Host "=" * 60
Write-Host "Windows 文件系统报告 - $(Get-Date)"
Write-Host "=" * 60
# 1. 获取磁盘信息
Write-Host "`n--- 磁盘使用情况 ---"
Get-PSDrive -PSProvider FileSystem | 
    Select-Object Name, Used, Free, @{N="Size";E={$_.Used + $_.Free}} |
    Format-Table -AutoSize
# 2. 获取逻辑磁盘详细信息
Write-Host "`n--- 逻辑磁盘详细信息 ---"
Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3" |
    Select-Object DeviceID, @{N="Size(GB)";E={[math]::Round($_.Size/1GB, 2)}},
        @{N="Free(GB)";E={[math]::Round($_.FreeSpace/1GB, 2)}},
        @{N="Used(%)";E={[math]::Round(($_.Size-$_.FreeSpace)/$_.Size*100, 2)}},
        FileSystem
# 3. 检查磁盘使用率超过90%的警告
Write-Host "`n--- 磁盘使用率警告 ---"
$disks = Get-WmiObject Win32_LogicalDisk -Filter "DriveType=3"
$warning = @()
foreach ($disk in $disks) {
    $usedPercent = ($disk.Size - $disk.FreeSpace) / $disk.Size * 100
    if ($usedPercent -gt 90) {
        $warning += $disk.DeviceID
        Write-Host "⚠️  警告: $($disk.DeviceID) 使用率: $([math]::Round($usedPercent, 2))%" -ForegroundColor Red
    }
}
# 4. 生成HTML报告
$html = @"
<!DOCTYPE html>
<html>
<head>Windows 文件系统报告</title>
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; margin: 20px; }
        h1 { color: #0078d4; }
        table { border-collapse: collapse; width: 100%; margin: 20px 0; }
        th { background-color: #0078d4; color: white; padding: 10px; }
        td { border: 1px solid #ddd; padding: 8px; }
        .warning { background-color: #fff3cd; color: #856404; }
    </style>
</head>
<body>
    <h1>Windows 文件系统报告</h1>
    <p>生成时间: $(Get-Date)</p>
"@
# 添加到HTML
$html += "<table><tr><th>盘符</th><th>大小(GB)</th><th>已用(GB)</th><th>可用(GB)</th><th>使用率(%)</th></tr>"
foreach ($disk in $disks) {
    $size = [math]::Round($disk.Size/1GB, 2)
    $free = [math]::Round($disk.FreeSpace/1GB, 2)
    $used = $size - $free
    $percent = [math]::Round(($used/$size)*100, 2)
    $class = if ($percent -gt 90) { "warning" } else { "" }
    $html += "<tr class='$class'><td>$($disk.DeviceID)</td><td>$size</td><td>$used</td><td>$free</td><td>$percent%</td></tr>"
}
$html += "</table></body></html>"
$html | Out-File -FilePath "filesystem_report_$(Get-Date -Format 'yyyyMMdd_HHmmss').html"

VBScript (适合旧系统)

' filesystem_report.vbs
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
WScript.Echo "=================================="
WScript.Echo "文件系统报告 - " & Now
WScript.Echo "=================================="
WScript.Echo ""
Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk Where DriveType=3")
For Each objDisk in colDisks
    WScript.Echo "盘符: " & objDisk.DeviceID
    WScript.Echo "文件系统: " & objDisk.FileSystem
    WScript.Echo "总大小: " & Round(objDisk.Size / 1073741824, 2) & " GB"
    WScript.Echo "可用空间: " & Round(objDisk.FreeSpace / 1073741824, 2) & " GB"
    WScript.Echo "已用空间: " & Round((objDisk.Size - objDisk.FreeSpace) / 1073741824, 2) & " GB"
    WScript.Echo "使用率: " & Round((objDisk.Size - objDisk.FreeSpace) / objDisk.Size * 100, 2) & "%"
    ' 检查是否超过90%
    If ((objDisk.Size - objDisk.FreeSpace) / objDisk.Size * 100) > 90 Then
        WScript.Echo "警告: 磁盘使用率超过90%!"
    End If
    WScript.Echo "-------------------"
Next
' 输出到文件
Set objFile = objFSO.CreateTextFile("filesystem_report.txt", True)
' ... 同样的内容写入文件 ...

定时执行报告

Linux (crontab)

# 每天8点生成报告
0 8 * * * /path/to/filesystem_report.sh

Windows (任务计划程序)

# 创建每天8点的任务
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\scripts\filesystem_report.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At 08:00AM
Register-ScheduledTask -TaskName "文件系统报告" -Action $action -Trigger $trigger

推荐使用方案

  1. 快速检查: 使用 df -h (Linux) 或 Get-PSDrive (Windows)
  2. 日常监控: 使用Python脚本生成JSON/HTML报告
  3. 报警系统: 结合使用率检查和邮件通知
  4. 自动化: 配置定时任务,自动生成和发送报告

选择哪种方法取决于你的环境、需求和熟悉程度,Python脚本通常是最灵活和可维护的选择。

抱歉,评论功能暂时关闭!