Отчёт по заполненности дисков
Проверяет место и inode на файловых системах и предупреждает о переполнении.
Что делает скрипт
Скрипт собирает данные df и lsblk, считает занятость в байтах и процентах, отдельно проверяет inode. Порог задаётся через --warn-percent, при превышении код возврата будет 1. Отчёт можно сохранить в JSON, ничего не удаляется и не монтируется.
Быстрый старт
python disk_report.py --warn-percent 85
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
python disk_report.pypython disk_report.py --warn-percent 90 --json report.jsonpython disk_report.py --no-inodes
Что понадобится
sudo apt install python3
sudo apt install util-linux
disk_report.py
#!/usr/bin/env python3
"""Отчёт по дискам и файловым системам без изменения системы."""
from __future__ import annotations
import argparse
import json
import shutil
import subprocess
from dataclasses import asdict, dataclass
from pathlib import Path
@dataclass
class FileSystem:
source: str
fstype: str
size: int
used: int
avail: int
percent: int
target: str
inodes_percent: int | None
def run(argv: list[str]) -> subprocess.CompletedProcess[str] | None:
try:
return subprocess.run(argv, capture_output=True, text=True, check=False)
except FileNotFoundError:
return None
def human(value: int) -> str:
size = float(value)
for unit in ("B", "KiB", "MiB", "GiB", "TiB", "PiB"):
if size < 1024 or unit == "PiB":
return f"{size:.1f} {unit}"
size /= 1024
return f"{value} B"
def df_filesystems() -> list[FileSystem]:
result = run(["df", "-PT", "-B1", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs"])
if result is None or result.returncode != 0:
return []
rows: list[FileSystem] = []
for line in result.stdout.splitlines()[1:]:
parts = line.split(None, 6)
if len(parts) != 7:
continue
source, fstype, size, used, avail, percent, target = parts
try:
rows.append(
FileSystem(
source=source,
fstype=fstype,
size=int(size),
used=int(used),
avail=int(avail),
percent=int(percent.rstrip("%")),
target=target,
inodes_percent=None,
)
)
except ValueError:
continue
return rows
def inode_map() -> dict[str, int]:
result = run(["df", "-Pi", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs"])
if result is None or result.returncode != 0:
return {}
values: dict[str, int] = {}
for line in result.stdout.splitlines()[1:]:
parts = line.split(None, 5)
if len(parts) != 6:
continue
_source, _inodes, _iused, _ifree, percent, target = parts
try:
values[target] = int(percent.rstrip("%"))
except ValueError:
continue
return values
def block_devices() -> list[dict]:
result = run(["lsblk", "-J", "-b", "-o", "NAME,PATH,TYPE,SIZE,FSTYPE,MOUNTPOINTS,RO,MODEL"])
if result is None or result.returncode != 0:
return []
try:
return json.loads(result.stdout).get("blockdevices", [])
except json.JSONDecodeError:
return []
def main() -> int:
parser = argparse.ArgumentParser(description="Отчёт по дискам Linux")
parser.add_argument("--warn-percent", type=int, default=85, help="Порог заполнения в процентах")
parser.add_argument("--no-inodes", action="store_true", help="Не проверять inode")
parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
args = parser.parse_args()
if shutil.which("df") is None:
print("df не найден. Установите coreutils.")
return 2
filesystems = df_filesystems()
inodes = {} if args.no_inodes else inode_map()
for item in filesystems:
item.inodes_percent = inodes.get(item.target)
devices = block_devices()
problems = 0
print(f"{'ТОЧКА':<24} {'ИСТОЧНИК':<26} {'ФС':<8} {'РАЗМЕР':>10} {'ЗАНЯТО':>10} {'СВОБОДНО':>10} {'%':>4} {'INODE':>6}")
print("-" * 120)
for item in filesystems:
inode_text = "-" if item.inodes_percent is None else f"{item.inodes_percent}%"
print(
f"{item.target:<24} {item.source:<26} {item.fstype:<8} "
f"{human(item.size):>10} {human(item.used):>10} {human(item.avail):>10} "
f"{item.percent:>3}% {inode_text:>6}"
)
if item.percent >= args.warn_percent:
print(f" [WARN] {item.target}: занято {item.percent}% (порог {args.warn_percent}%)")
problems += 1
if item.inodes_percent is not None and item.inodes_percent >= args.warn_percent:
print(f" [WARN] {item.target}: inode заняты на {item.inodes_percent}%")
problems += 1
if devices:
print("\nБлочные устройства:")
for device in devices:
name = device.get("name", "?")
size = device.get("size") or 0
fstype = device.get("fstype") or "-"
model = (device.get("model") or "").strip()
print(f" /dev/{name:<12} {human(int(size)):>10} {fstype:<8} {model}")
if args.json:
args.json.write_text(
json.dumps(
{
"filesystems": [asdict(item) for item in filesystems],
"blockdevices": devices,
"warn_percent": args.warn_percent,
"problems": problems,
},
ensure_ascii=False,
indent=2,
)
+ "\n",
encoding="utf-8",
)
print(f"\nJSON сохранён: {args.json}")
if problems:
print(f"\nФайловых систем с замечаниями: {problems}")
return 1
print("\nПереполнения не обнаружены.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.