Linux

Аудит задач cron

Собирает задачи из системных файлов и crontab и отмечает рискованные команды.

Python Linux Средний
Скачать cron_audit.py
Описание

Что делает скрипт

Скрипт читает /etc/crontab, /etc/cron.d, spool-каталоги и crontab текущего пользователя, разбирает расписание и команды. Для каждой записи показывается источник и предупреждения: запуск скачанного кода, использование /tmp, отсутствие исполняемого файла. Ничего не изменяет и не запускает.

Запуск

Быстрый старт

python cron_audit.py

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python cron_audit.py
  • python cron_audit.py --warnings-only
  • python cron_audit.py --json report.json
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
Linux sudo apt install python3
cron crontab для чтения задач текущего пользователя
Linux sudo apt install cron
Исходник

cron_audit.py

#!/usr/bin/env python3
"""Аудит задач cron без изменения системы."""
from __future__ import annotations

import argparse
import json
import os
import re
import shlex
import stat
import subprocess
from dataclasses import asdict, dataclass
from pathlib import Path

SYSTEM_FILES = [Path("/etc/crontab")]
CRON_DIRS = [Path("/etc/cron.d")]
SPOOL_DIRS = [Path("/var/spool/cron/crontabs"), Path("/var/spool/cron")]
DANGEROUS = re.compile(r"(curl|wget)[^|]*\|\s*(ba)?sh", re.IGNORECASE)


@dataclass
class Entry:
    source: str
    schedule: str
    user: str
    command: str
    note: str


def read_text(path: Path) -> str:
    try:
        return path.read_text(encoding="utf-8", errors="replace")
    except OSError:
        return ""


def command_notes(command: str) -> str:
    notes = []
    if DANGEROUS.search(command):
        notes.append("запуск скачанного кода")
    if "/tmp/" in command or "/var/tmp/" in command:
        notes.append("использует временный каталог")
    if "base64" in command and ("-d" in command or "--decode" in command):
        notes.append("декодирование base64")
    try:
        tokens = shlex.split(command)
    except ValueError:
        tokens = command.split()
    if tokens and tokens[0].startswith("/"):
        binary = Path(tokens[0])
        if not binary.exists():
            notes.append("файл команды не найден")
        else:
            try:
                mode = binary.stat().st_mode
                if mode & stat.S_IWOTH:
                    notes.append("команда доступна на запись всем")
            except OSError:
                pass
    return ", ".join(notes)


def parse_file(path: Path, default_user: str, source: str) -> list[Entry]:
    entries: list[Entry] = []
    text = read_text(path)
    if not text:
        return entries
    for raw in text.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        first = line.split(None, 1)[0]
        if "=" in first and not first.startswith("/") and not line.startswith("@"):
            continue
        if line.startswith("@"):
            parts = line.split(None, 2)
            if len(parts) == 3:
                schedule, user, command = parts
            elif len(parts) == 2:
                schedule, command = parts
                user = default_user
            else:
                continue
        else:
            parts = line.split(None, 6)
            if len(parts) == 7:
                schedule = " ".join(parts[:5])
                user = parts[5]
                command = parts[6]
            elif len(parts) == 6:
                schedule = " ".join(parts[:5])
                user = default_user
                command = parts[5]
            else:
                continue
        entries.append(Entry(source, schedule, user, command, command_notes(command)))
    return entries


def user_crontab() -> list[Entry]:
    result = subprocess.run(["crontab", "-l"], capture_output=True, text=True, check=False)
    if result.returncode != 0 or not result.stdout:
        return []
    entries = []
    for raw in result.stdout.splitlines():
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("@"):
            parts = line.split(None, 1)
            if len(parts) == 2:
                entries.append(Entry("crontab текущего пользователя", parts[0], os.environ.get("USER", "user"), parts[1], command_notes(parts[1])))
            continue
        parts = line.split(None, 5)
        if len(parts) == 6:
            schedule = " ".join(parts[:5])
            command = parts[5]
            entries.append(Entry("crontab текущего пользователя", schedule, os.environ.get("USER", "user"), command, command_notes(command)))
    return entries


def collect() -> tuple[list[Entry], list[str]]:
    entries: list[Entry] = []
    problems: list[str] = []
    for path in SYSTEM_FILES:
        if path.exists():
            if not os.access(path, os.R_OK):
                problems.append(f"нет доступа на чтение: {path}")
                continue
            entries.extend(parse_file(path, "root", str(path)))
    for directory in CRON_DIRS:
        try:
            if not directory.is_dir():
                continue
            children = sorted(directory.iterdir())
        except OSError as error:
            problems.append(f"нет доступа к {directory}: {error}")
            continue
        for path in children:
            if not path.is_file() or path.name.startswith("."):
                continue
            if not os.access(path, os.R_OK):
                problems.append(f"нет доступа на чтение: {path}")
                continue
            entries.extend(parse_file(path, "root", str(path)))
    for directory in SPOOL_DIRS:
        try:
            if not directory.is_dir():
                continue
            children = sorted(directory.iterdir())
        except OSError as error:
            problems.append(f"нет доступа к {directory}: {error}")
            continue
        for path in children:
            if not path.is_file():
                continue
            if not os.access(path, os.R_OK):
                problems.append(f"нет доступа на чтение: {path}")
                continue
            entries.extend(parse_file(path, path.name, str(path)))
    entries.extend(user_crontab())
    entries.sort(key=lambda item: (item.source, item.schedule))
    return entries, problems


def main() -> int:
    parser = argparse.ArgumentParser(description="Аудит задач cron")
    parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
    parser.add_argument("--warnings-only", action="store_true", help="Показать только записи с замечаниями")
    args = parser.parse_args()

    entries, problems = collect()
    shown = [item for item in entries if item.note] if args.warnings_only else entries

    if not shown:
        print("Задачи cron не найдены." if not entries else "Записей с замечаниями нет.")
    else:
        print(f"{'ИСТОЧНИК':<34} {'РАСПИСАНИЕ':<18} {'ПОЛЬЗОВАТЕЛЬ':<12} КОМАНДА")
        print("-" * 110)
        for item in shown:
            command = item.command if len(item.command) <= 70 else item.command[:67] + "..."
            print(f"{item.source:<34} {item.schedule:<18} {item.user:<12} {command}")
            if item.note:
                print(f"{'':<34} замечание: {item.note}")

    if problems:
        print("\nОграничения доступа (для полного аудита запустите от root):")
        for problem in problems:
            print(f" - {problem}")

    warning_count = sum(1 for item in entries if item.note)
    print(f"\nВсего записей: {len(entries)}, с замечаниями: {warning_count}")

    if args.json:
        args.json.write_text(
            json.dumps(
                {
                    "entries": [asdict(item) for item in entries],
                    "problems": problems,
                    "warning_count": warning_count,
                },
                ensure_ascii=False,
                indent=2,
            )
            + "\n",
            encoding="utf-8",
        )
        print(f"Отчёт сохранён: {args.json}")

    return 1 if warning_count else 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get linux-cron-audit
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

Linux

Bash и Python для серверов, рабочих станций и повседневных задач Linux.