Аудит паролей и сроков
Проверяет пустые пароли, блокировки, срок действия и устаревшие пароли.
Что делает скрипт
Скрипт читает /etc/shadow, поэтому запускается от root, и разбирает дату последней смены, максимальный срок, срок предупреждения и дату истечения учётной записи. Хеши не выводятся: только имя пользователя и статус. Пустые пароли и просроченные записи отмечаются отдельно.
Быстрый старт
sudo python3 audit_passwords.py
Скачайте файл, откройте терминал в папке со скриптом и выполните команду.
В Linux и macOS интерпретатор может называться python3, в Windows - python или py.
Другие варианты
sudo python3 audit_passwords.py --warn-days 21sudo python3 audit_passwords.py --max-age 180 --json passwords.json
Что понадобится
sudo apt install python3
audit_passwords.py
#!/usr/bin/env python3
"""Аудит паролей в /etc/shadow без вывода хешей."""
from __future__ import annotations
import argparse
import datetime as dt
import json
import pwd
from pathlib import Path
def account_shell(name: str) -> str:
try:
return pwd.getpwnam(name).pw_shell or "?"
except KeyError:
return "?"
def parse_int(value: str, default: int = 0) -> int:
try:
return int(value)
except (TypeError, ValueError):
return default
def main() -> int:
parser = argparse.ArgumentParser(description="Аудит паролей и сроков действия")
parser.add_argument("--shadow", type=Path, default=Path("/etc/shadow"), help="Путь к файлу shadow")
parser.add_argument("--max-age", type=int, default=365, help="Предупреждать, если пароль старше N дней")
parser.add_argument("--warn-days", type=int, default=14, help="Порог предупреждения об истечении")
parser.add_argument("--json", type=Path, help="Сохранить отчёт в JSON")
args = parser.parse_args()
try:
lines = args.shadow.read_text(encoding="utf-8", errors="replace").splitlines()
except PermissionError:
print(f"Нет доступа к {args.shadow}. Запустите скрипт от root.")
return 2
except OSError as error:
print(f"Не удалось прочитать {args.shadow}: {error}")
return 2
today = dt.date.today()
epoch = dt.date(1970, 1, 1)
today_days = (today - epoch).days
problems: list[dict[str, object]] = []
total = 0
for line in lines:
fields = line.split(":")
if len(fields) < 9:
continue
name, hashed, last_text, _min_text, max_text, _warn_text, _inactive, expire_text, _flag = fields[:9]
if not name or name.startswith("#"):
continue
total += 1
last = parse_int(last_text)
max_days = parse_int(max_text, 99999)
expire = parse_int(expire_text)
locked = hashed.startswith("!") or hashed.startswith("*")
empty = hashed == ""
shell = account_shell(name)
reasons: list[str] = []
if empty:
reasons.append("пустой пароль")
if last == 0 and not locked:
reasons.append("дата смены не задана")
if last > 0 and max_days > 0 and max_days < 99999:
change_due = last + max_days
if change_due < today_days:
reasons.append("пароль просрочен")
elif change_due - today_days <= args.warn_days:
reasons.append(f"пароль истекает через {change_due - today_days} дн.")
if last > 0:
age = today_days - last
if age > args.max_age:
reasons.append(f"пароль не менялся {age} дн.")
if expire > 0 and expire < today_days:
reasons.append("учётная запись истекла")
if reasons:
problems.append(
{
"user": name,
"shell": shell,
"locked": locked,
"empty": empty,
"reasons": reasons,
}
)
print(f"Файл: {args.shadow}")
print(f"Учётных записей: {total}")
print(f"С замечаниями: {len(problems)}")
if problems:
print()
for item in problems:
state = "заблокирована" if item["locked"] else "активна"
reasons = "; ".join(item["reasons"]) # type: ignore[arg-type]
print(f" {item['user']} ({state}, {item['shell']}): {reasons}")
else:
print("Замечаний нет.")
if args.json:
payload = {"shadow": str(args.shadow), "total": total, "problems": problems}
args.json.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"JSON сохранён: {args.json}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.