4 Commits

Author SHA1 Message Date
PTah 6511d34ca7 fix: suppress sudo Telegram during SAC agent update (2.2.3-SAC)
Whitelist SAC maintenance commands in ssh-monitor-perms and monitor_sudo; pre-commit uses working python on Windows.
2026-07-08 12:25:06 +10:00
PTah 440577ac5a chore: install-git-hooks.ps1 for Windows 2026-07-08 12:14:11 +10:00
PTah 5ac4792c3c chore: auto manifest on version bump; local manual script only
contrib/manifest/generate.py + pre-commit hook; install-git-hooks.sh creates
.local/build-release-manifest.sh (gitignored). Remove scripts/ from remote.
2026-07-08 12:05:21 +10:00
PTah 0399a6d384 fix: manifest SHA256 from git blobs (CRLF/LF) — release 2.2.2-SAC
Manifest was hashed from Windows working tree while Linux checkout uses
git blobs; verify failed with sha256 mismatch. build-release-manifest.sh
now hashes :index/HEAD; .gitattributes enforces LF for agent scripts.
2026-07-08 12:00:51 +10:00
18 changed files with 382 additions and 98 deletions
+4
View File
@@ -0,0 +1,4 @@
# Агентские скрипты — LF в git и на Linux (manifest SHA256 = git blob).
ssh-monitor text eol=lf
*.sh text eol=lf
version.txt text eol=lf
+3 -1
View File
@@ -11,4 +11,6 @@ ssh-monitor-*.tar.gz
# Локальный загрузчик Rutube / yt-dlp — живёт в другом репозитории # Локальный загрузчик Rutube / yt-dlp — живёт в другом репозитории
rutube-download.py rutube-download.py
.ytdl-archive.txt .ytdl-archive.txt
.cursorignore # Локальные инструменты разработки (не в Gitea/GitHub)
.local/
scripts/build-release-manifest.sh
+2 -1
View File
@@ -6,7 +6,8 @@ DIST := ssh-monitor-$(VERSION).tar.gz
dist: $(DIST) dist: $(DIST)
manifest: manifest:
./scripts/build-release-manifest.sh @test -x .local/build-release-manifest.sh || (echo "Сначала: ./contrib/install-git-hooks.sh" >&2; exit 1)
./.local/build-release-manifest.sh
$(DIST): ssh-monitor $(DIST): ssh-monitor
git archive --format=tar.gz --prefix=ssh-monitor-$(VERSION)/ -o $(DIST) HEAD git archive --format=tar.gz --prefix=ssh-monitor-$(VERSION)/ -o $(DIST) HEAD
+4 -2
View File
@@ -1,6 +1,6 @@
# ssh-monitor # ssh-monitor
**Версия:** `2.2.1-SAC` **Версия:** `2.2.3-SAC`
Bash-мониторинг **SSH**, **sudo**, **systemd-logind**: Telegram/email, бан IP (ipset), ежедневный отчёт, heartbeat. Bash-мониторинг **SSH**, **sudo**, **systemd-logind**: Telegram/email, бан IP (ipset), ежедневный отчёт, heartbeat.
@@ -165,7 +165,9 @@ bash -n ./ssh-monitor
## Релизный архив ## Релизный архив
Версия задаётся в **`SSH_MONITOR_VERSION`** в файле **`ssh-monitor`** и дублируется в **`version.txt`** (та же строка, что в шапке README). Модуль **`sac-client.sh`** использует ту же версию для SAC `product_version`. Сборка tarball из текущего git-дерева: Версия задаётся в **`SSH_MONITOR_VERSION`** в файле **`ssh-monitor`** и дублируется в **`version.txt`** (та же строка, что в шапке README). Модуль **`sac-client.sh`** использует ту же версию для SAC `product_version`. **Release manifest** (`release/manifest-*.json`): [docs/release-manifest.ru.md](docs/release-manifest.ru.md) — после clone: `.\contrib\install-git-hooks.ps1` (Windows) или `./contrib/install-git-hooks.sh` (Linux/Git Bash).
Сборка tarball из текущего git-дерева:
```bash ```bash
make dist make dist
+66
View File
@@ -0,0 +1,66 @@
#!/bin/bash
# Автогенерация release/manifest-VERSION.json при bump версии (version.txt / SSH_MONITOR_VERSION).
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
_staged() {
git diff --cached --name-only -- "$@"
}
_version_bump_staged() {
if _staged version.txt | grep -q .; then
return 0
fi
if _staged ssh-monitor | grep -q .; then
if git diff --cached -- ssh-monitor | grep -qE '^[+-].*SSH_MONITOR_VERSION='; then
return 0
fi
fi
return 1
}
_agent_files_staged() {
local f
for f in ssh-monitor sac-client.sh update_ssh_monitor.sh ssh-monitor-watchdog ssh-monitor-perms.sh; do
if _staged "$f" | grep -q .; then
return 0
fi
done
return 1
}
_version_bump_staged || _agent_files_staged || exit 0
_find_python() {
local c
for c in python3 python; do
if command -v "$c" >/dev/null 2>&1 && "$c" -c 'import sys' >/dev/null 2>&1; then
echo "$c"
return 0
fi
done
return 1
}
PY="$(_find_python)" || {
echo "pre-commit: python нужен для manifest (рабочий python/python3 не найден)" >&2
exit 1
}
"$PY" "$ROOT/contrib/manifest/generate.py"
VER="$(tr -d '\r\n' <"$ROOT/version.txt")"
[ -n "$VER" ] || {
echo "pre-commit: version.txt пуст — не могу добавить manifest" >&2
exit 1
}
MANIFEST="release/manifest-${VER}.json"
if [ ! -f "$MANIFEST" ]; then
echo "pre-commit: не создан $MANIFEST" >&2
exit 1
fi
git add "$MANIFEST"
echo "pre-commit: обновлён $MANIFEST (версия $VER)"
+54
View File
@@ -0,0 +1,54 @@
# Install git hooks + local manifest wrappers (not committed to git).
# Run from repo root: .\contrib\install-git-hooks.ps1
$ErrorActionPreference = "Stop"
$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
$HookSrc = Join-Path $Root "contrib\hooks\pre-commit"
$HookDst = Join-Path $Root ".git\hooks\pre-commit"
$LocalDir = Join-Path $Root ".local"
$LocalScript = Join-Path $LocalDir "build-release-manifest.ps1"
$LocalScriptSh = Join-Path $LocalDir "build-release-manifest.sh"
if (-not (Test-Path (Join-Path $Root ".git"))) {
throw "Not a git repository: $Root"
}
if (-not (Test-Path $HookSrc)) {
throw "Missing hook file: $HookSrc"
}
New-Item -ItemType Directory -Force -Path (Split-Path $HookDst) | Out-Null
Copy-Item -Force $HookSrc $HookDst
New-Item -ItemType Directory -Force -Path $LocalDir | Out-Null
@'
# Local manifest wrapper (gitignored). Manual generation on Windows.
$ErrorActionPreference = "Stop"
$Root = git -C "$PSScriptRoot\.." rev-parse --show-toplevel 2>$null
if (-not $Root) {
$Root = (Resolve-Path (Join-Path $PSScriptRoot "..")).Path
}
$py = Get-Command python -ErrorAction SilentlyContinue
if (-not $py) { $py = Get-Command python3 -ErrorAction SilentlyContinue }
if (-not $py) { throw "python not found in PATH" }
& $py.Source (Join-Path $Root "contrib\manifest\generate.py") @args
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
'@ | Set-Content -Path $LocalScript -Encoding UTF8
@'
#!/bin/bash
# Local manifest wrapper (gitignored). Git Bash.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
exec python3 "$ROOT/contrib/manifest/generate.py" "$@"
'@ | Set-Content -Path $LocalScriptSh -Encoding ASCII -NoNewline
Add-Content -Path $LocalScriptSh -Value "`n" -NoNewline
Write-Host "OK: pre-commit hook -> $HookDst"
Write-Host "OK: manual script (PS) -> $LocalScript"
Write-Host "OK: manual script (sh) -> $LocalScriptSh"
Write-Host ""
Write-Host "Manual: .\.local\build-release-manifest.ps1"
Write-Host " python contrib\manifest\generate.py"
Write-Host "Pre-commit runs on version bump (python required in PATH)."
+31
View File
@@ -0,0 +1,31 @@
#!/bin/bash
# Установка git hooks и локального скрипта ручной генерации manifest (не в git).
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOOK_SRC="$ROOT/contrib/hooks/pre-commit"
HOOK_DST="$ROOT/.git/hooks/pre-commit"
LOCAL_DIR="$ROOT/.local"
LOCAL_SCRIPT="$LOCAL_DIR/build-release-manifest.sh"
if [ ! -d "$ROOT/.git" ]; then
echo "ERROR: не git-репозиторий: $ROOT" >&2
exit 1
fi
mkdir -p "$LOCAL_DIR"
cat >"$LOCAL_SCRIPT" <<'EOF'
#!/bin/bash
# Локальный wrapper (не коммитится). Ручная генерация manifest.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
exec python3 "$ROOT/contrib/manifest/generate.py" "$@"
EOF
chmod +x "$LOCAL_SCRIPT"
cp "$HOOK_SRC" "$HOOK_DST"
chmod +x "$HOOK_DST"
echo "OK: pre-commit hook → $HOOK_DST"
echo "OK: ручной скрипт → $LOCAL_SCRIPT (в .gitignore, не уйдёт в Gitea/GitHub)"
echo "После clone: ./contrib/install-git-hooks.sh или .\\contrib\\install-git-hooks.ps1 (Windows)"
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Генерация release/manifest-VERSION.json (SHA256 git blob = checkout на Linux)."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import subprocess
import sys
from pathlib import Path
MANIFEST_FILES = (
"ssh-monitor",
"sac-client.sh",
"update_ssh_monitor.sh",
"ssh-monitor-watchdog",
"ssh-monitor-perms.sh",
)
def repo_root() -> Path:
return Path(
subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip()
)
def read_version(root: Path, explicit: str | None) -> str:
if explicit:
return explicit.strip()
vt = root / "version.txt"
if vt.is_file():
v = vt.read_text(encoding="utf-8").strip()
if v:
return v
ssh = root / "ssh-monitor"
if ssh.is_file():
for line in ssh.read_text(encoding="utf-8", errors="replace").splitlines():
if line.strip().startswith("SSH_MONITOR_VERSION="):
v = line.split("=", 1)[1].strip().strip("\"'")
if v:
return v
raise SystemExit("ERROR: укажите VERSION или заполните version.txt / SSH_MONITOR_VERSION")
def file_bytes_from_git(root: Path, name: str) -> bytes | None:
for ref in (f":{name}", f"HEAD:{name}"):
try:
return subprocess.check_output(["git", "-C", str(root), "show", ref])
except subprocess.CalledProcessError:
continue
return None
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_release_file(root: Path, name: str) -> str:
blob = file_bytes_from_git(root, name)
if blob is not None:
return sha256_bytes(blob)
path = root / name
if not path.is_file():
raise SystemExit(f"ERROR: нет файла {name} (ни в git index/HEAD, ни на диске)")
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def main() -> None:
parser = argparse.ArgumentParser(description="Сгенерировать release/manifest-VERSION.json")
parser.add_argument("version", nargs="?", help="Версия (по умолчанию из version.txt)")
parser.add_argument(
"--pin-commit",
action="store_true",
help="Записать git_commit=HEAD (после коммита; в pre-commit не используется)",
)
args = parser.parse_args()
root = repo_root()
version = read_version(root, args.version)
for name in MANIFEST_FILES:
if file_bytes_from_git(root, name) is None and not (root / name).is_file():
raise SystemExit(f"ERROR: нет файла {name}")
git_commit = ""
if args.pin_commit:
try:
git_commit = subprocess.check_output(
["git", "-C", str(root), "rev-parse", "HEAD"], text=True
).strip()
except subprocess.CalledProcessError:
pass
manifest = {
"version": version,
"git_commit": git_commit,
"files": {name: f"sha256:{sha256_release_file(root, name)}" for name in MANIFEST_FILES},
}
out = root / "release" / f"manifest-{version}.json"
out.parent.mkdir(parents=True, exist_ok=True)
with out.open("w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, ensure_ascii=False)
f.write("\n")
pin = git_commit[:12] if git_commit else "(empty)"
print(f"Wrote {out.relative_to(root)} git_commit={pin}")
if __name__ == "__main__":
main()
+4 -5
View File
@@ -91,13 +91,12 @@ Updater читает **`GIT_REF`**, **`GIT_VERIFY_MODE`**, **`GIT_ALLOW_RESET`**
- Файл не найден → WARN, update продолжается (или exit 1 при **`RELEASE_MANIFEST_STRICT=1`**). - Файл не найден → WARN, update продолжается (или exit 1 при **`RELEASE_MANIFEST_STRICT=1`**).
- Копирование **`update_ssh_monitor.sh`** в `/opt/scripts/` и re-exec — только если manifest для версии был и прошёл verify. - Копирование **`update_ssh_monitor.sh`** в `/opt/scripts/` и re-exec — только если manifest для версии был и прошёл verify.
Генерация при релизе (после **финального** коммита кода, чтобы `git_commit` в manifest совпал с HEAD): Генерация manifest — см. [release-manifest.ru.md](release-manifest.ru.md). После `./contrib/install-git-hooks.sh` manifest обновляется **автоматически** при bump версии в pre-commit. Ручной wrapper: `.local/build-release-manifest.sh` (не в git).
```bash ```bash
git commit -m "release: 2.2.0-SAC" ./contrib/install-git-hooks.sh # один раз после clone
./scripts/build-release-manifest.sh 2.2.0-SAC # bump version.txt + ssh-monitor → git commit (hook добавит manifest)
git add release/manifest-2.2.0-SAC.json && git commit -m "release: manifest 2.2.0-SAC" git tag 2.2.3-SAC
git tag 2.2.0-SAC
``` ```
### Примеры для прода ### Примеры для прода
+46
View File
@@ -0,0 +1,46 @@
# Release manifest
Файлы `release/manifest-VERSION.json` — SHA256 агентских скриптов **как в git** (после `checkout` на Linux). Updater сверяет их до копирования на хост.
## Автоматически (рекомендуется)
Один раз после clone:
**Linux / Git Bash:**
```bash
./contrib/install-git-hooks.sh
```
**Windows (PowerShell):**
```powershell
.\contrib\install-git-hooks.ps1
```
При коммите, если изменились **`version.txt`**, **`SSH_MONITOR_VERSION`** в `ssh-monitor` или любой из агентских файлов (`ssh-monitor`, `*.sh` из списка manifest), **pre-commit** вызовет `contrib/manifest/generate.py` и добавит `release/manifest-{версия}.json` в коммит.
## Ручная генерация (локально)
Скрипты **`.local/build-release-manifest.ps1`** (Windows) и **`.local/build-release-manifest.sh`** (Git Bash) создаются установщиком и **не коммитятся** (см. `.gitignore`).
```powershell
.\.local\build-release-manifest.ps1
.\.local\build-release-manifest.ps1 2.2.3-SAC
```
```bash
./.local/build-release-manifest.sh
```
Ядро генерации в репозитории: `contrib/manifest/generate.py` (используется hook и локальным wrapper).
## Релиз (чек-лист)
1. Bump `SSH_MONITOR_VERSION` + `version.txt`
2. `git add` изменённые файлы
3. `git commit` — hook обновит manifest (или вручную `.local/build-release-manifest.sh`)
4. `git tag X.Y.Z-SAC`
5. Push в kalinamall (+ GitHub при необходимости)
Поле `git_commit` в manifest по умолчанию **пустое** (проверяются только SHA256 файлов). Опционально после коммита: `python3 contrib/manifest/generate.py --pin-commit`.
См. также [auto-update.ru.md](auto-update.ru.md).
+2 -1
View File
@@ -25,6 +25,7 @@
| **2.1.7-SAC** | Фаза 1 + выбранное из Фазы 4 | Права, `REPO_URL` обязателен, webhook, docs | ✅ реализовано | | **2.1.7-SAC** | Фаза 1 + выбранное из Фазы 4 | Права, `REPO_URL` обязателен, webhook, docs | ✅ реализовано |
| **2.1.8-SAC** | Дополнение к 1.1 | SAC-first update: hardening прав на каждом прогоне updater | ✅ реализовано | | **2.1.8-SAC** | Дополнение к 1.1 | SAC-first update: hardening прав на каждом прогоне updater | ✅ реализовано |
| **2.1.9-SAC** | Дополнение к 1.x | Watchdog: `🖥️ Сервер:` в Telegram (как у агента) | ✅ реализовано | | **2.1.9-SAC** | Дополнение к 1.x | Watchdog: `🖥️ Сервер:` в Telegram (как у агента) | ✅ реализовано |
| **2.2.3-SAC** | Дополнение к 2.2.x | Подавление sudo TG при SAC bootstrap/update | ✅ реализовано |
| **2.2.1-SAC** | Дополнение к 2.2.0 | Подавление lifecycle/watchdog TG при SAC-update | ✅ реализовано | | **2.2.1-SAC** | Дополнение к 2.2.0 | Подавление lifecycle/watchdog TG при SAC-update | ✅ реализовано |
| **2.2.0-SAC** | **Фаза 2** | Manifest, pinned ref, без слепого `reset --hard` | ✅ реализовано | | **2.2.0-SAC** | **Фаза 2** | Manifest, pinned ref, без слепого `reset --hard` | ✅ реализовано |
| **2.3.0-SAC** | Фаза 3 | Парсер конфига без `source` (minor breaking) | | **2.3.0-SAC** | Фаза 3 | Парсер конфига без `source` (minor breaking) |
@@ -142,7 +143,7 @@ Backlog по ingest при массовом update (SAC + ops): [ingest-mass-upd
- [x] Публиковать manifest при каждом релизе (в git, рядом с тегом) - [x] Публиковать manifest при каждом релизе (в git, рядом с тегом)
- [x] Updater: после checkout сверять SHA256 файлов из клона с manifest **до** копирования в `/usr/local/bin` - [x] Updater: после checkout сверять SHA256 файлов из клона с manifest **до** копирования в `/usr/local/bin`
- [x] Несовпадение → exit 1, ничего не перезаписывать - [x] Несовпадение → exit 1, ничего не перезаписывать
- [x] Скрипт/цель в `Makefile` или `scripts/build-release-manifest.sh` для генерации - [x] Скрипт/цель в `Makefile` + `contrib/manifest/generate.py`; pre-commit hook; ручной `.local/` (не в remote)
**Связь с 2.4:** manifest из **того же** `REPO_URL` защищает от подмены файлов в clone и от «не того» коммита; не защищает от полной компрометации git-сервера (для этого GPG). **Связь с 2.4:** manifest из **того же** `REPO_URL` защищает от подмены файлов в clone и от «не того» коммита; не защищает от полной компрометации git-сервера (для этого GPG).
+11
View File
@@ -0,0 +1,11 @@
{
"version": "2.2.2-SAC",
"git_commit": "",
"files": {
"ssh-monitor": "sha256:be35da47fb1cf370628795bfdfe34195a7ba098c666bd8aa092929a168a10ef6",
"sac-client.sh": "sha256:4c481effd0e50b3db8cfa3baf3c5f228892530939df6f534a5d3d3d8a79db048",
"update_ssh_monitor.sh": "sha256:510d63b43ea02e5aaa4385bcc6c9396ad99637c377c9880125cb2168e9d422cd",
"ssh-monitor-watchdog": "sha256:41aa139cab0fb275249780953fceb3f8ebe01c49bf96f901dd3cf4d2fb3a9274",
"ssh-monitor-perms.sh": "sha256:53ebf15138d59be1610e5bc14a107b942d9a7fd039683abfd2fdd0aa0b54b933"
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"version": "2.2.3-SAC",
"git_commit": "",
"files": {
"ssh-monitor": "sha256:875252eb23640cbae34bcaaf71d07b091c71e04c29d5d5d5e90851083c5bfc21",
"sac-client.sh": "sha256:4c481effd0e50b3db8cfa3baf3c5f228892530939df6f534a5d3d3d8a79db048",
"update_ssh_monitor.sh": "sha256:76c610ed229d510c41ddd0d10db2b68d48c08b89eb1c8252341ce85f088bf6cd",
"ssh-monitor-watchdog": "sha256:41aa139cab0fb275249780953fceb3f8ebe01c49bf96f901dd3cf4d2fb3a9274",
"ssh-monitor-perms.sh": "sha256:a1ca9e72a9bd7162324c308849cfeebd449228c308edb03191171e9d3187658c"
}
}
-82
View File
@@ -1,82 +0,0 @@
#!/bin/bash
# Генерация release/manifest-VERSION.json (SHA256 файлов + git commit HEAD).
# Запуск из корня репозитория: ./scripts/build-release-manifest.sh [VERSION]
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
version="${1:-}"
if [ -z "$version" ]; then
version="$(tr -d '\r\n' <version.txt 2>/dev/null || true)"
fi
if [ -z "$version" ]; then
version="$(grep -E '^[[:space:]]*SSH_MONITOR_VERSION=' ssh-monitor 2>/dev/null | head -1 | sed -E 's/^[^=]*=//; s/^["'\'']//; s/["'\'']$//; s/^[[:space:]]+//; s/[[:space:]]+$//')"
fi
[ -n "$version" ] || {
echo "ERROR: укажите VERSION или заполните version.txt" >&2
exit 1
}
FILES=(
ssh-monitor
sac-client.sh
update_ssh_monitor.sh
ssh-monitor-watchdog
ssh-monitor-perms.sh
)
for f in "${FILES[@]}"; do
[ -f "$f" ] || {
echo "ERROR: нет файла $f" >&2
exit 1
}
done
git_commit=""
if git rev-parse HEAD >/dev/null 2>&1; then
git_commit="$(git rev-parse HEAD)"
fi
out="release/manifest-${version}.json"
mkdir -p release
export MANIFEST_ROOT="$ROOT"
export MANIFEST_VERSION="$version"
export MANIFEST_GIT_COMMIT="$git_commit"
export MANIFEST_OUT="$out"
export MANIFEST_FILES="${FILES[*]}"
python3 <<'PY'
import hashlib
import json
import os
root = os.environ["MANIFEST_ROOT"]
version = os.environ["MANIFEST_VERSION"]
git_commit = os.environ.get("MANIFEST_GIT_COMMIT", "")
files = os.environ["MANIFEST_FILES"].split()
out = os.environ["MANIFEST_OUT"]
def sha256_file(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
manifest = {
"version": version,
"git_commit": git_commit,
"files": {},
}
for name in files:
path = os.path.join(root, name)
manifest["files"][name] = f"sha256:{sha256_file(path)}"
with open(out, "w", encoding="utf-8") as f:
json.dump(manifest, f, indent=2, ensure_ascii=False)
f.write("\n")
print(f"Wrote {out} commit={git_commit[:12] if git_commit else '?'}")
PY
+5 -1
View File
@@ -7,7 +7,7 @@ IFS=$'\n\t'
# ============================================ # ============================================
CONFIG_FILE="/etc/ssh-monitor.conf" CONFIG_FILE="/etc/ssh-monitor.conf"
SSH_MONITOR_VERSION="2.2.1-SAC" SSH_MONITOR_VERSION="2.2.3-SAC"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "$SCRIPT_DIR/ssh-monitor-perms.sh" ]; then if [ -f "$SCRIPT_DIR/ssh-monitor-perms.sh" ]; then
@@ -1521,6 +1521,10 @@ monitor_sudo() {
fi fi
if [ -n "$user" ] && [ -n "${sudo_cmd:-}" ]; then if [ -n "$user" ] && [ -n "${sudo_cmd:-}" ]; then
if ssh_monitor_sudo_is_sac_maintenance "$sudo_cmd" 2>/dev/null; then
write_log "SUDO: пропуск SAC/update maintenance ($user): ${sudo_cmd:0:80}…"
continue
fi
local message=" ⚠️ ИСПОЛЬЗОВАНИЕ SUDO "$'\n' local message=" ⚠️ ИСПОЛЬЗОВАНИЕ SUDO "$'\n'
message="${message}👤 Пользователь: ${user}"$'\n' message="${message}👤 Пользователь: ${user}"$'\n'
if [ -n "$run_as" ]; then if [ -n "$run_as" ]; then
+16
View File
@@ -205,3 +205,19 @@ ssh_monitor_update_mark_end() {
f="$(ssh_monitor_update_state_file)" f="$(ssh_monitor_update_state_file)"
rm -f "$f" 2>/dev/null || true rm -f "$f" 2>/dev/null || true
} }
# SAC/cron update: не слать sudo-alert на штатные команды updater/bootstrap.
ssh_monitor_sudo_is_sac_maintenance() {
local cmd="$1"
[ -n "$cmd" ] || return 1
if ssh_monitor_update_in_progress 2>/dev/null; then
return 0
fi
case "$cmd" in
*update_ssh_monitor.sh* | *UPDATE_VIA_SAC* | *update_script.log* | \
*"/opt/scripts/update"*"ssh-monitor"* | *agent-update-in-progress*)
return 0
;;
esac
return 1
}
+5 -4
View File
@@ -1570,10 +1570,6 @@ update_script() {
load_git_verify_settings load_git_verify_settings
load_ssh_monitor_perms_lib || true load_ssh_monitor_perms_lib || true
if declare -F ssh_monitor_update_mark_begin >/dev/null 2>&1; then
ssh_monitor_update_mark_begin
log_action "agent-update: state file установлен (подавление lifecycle/watchdog)"
fi
log_action "Старт обновления (deploy=$DEPLOY_MODE, debug=$DEBUG, git_ref=${GIT_REF:-$GIT_BRANCH})" log_action "Старт обновления (deploy=$DEPLOY_MODE, debug=$DEBUG, git_ref=${GIT_REF:-$GIT_BRANCH})"
debug_step "Запуск функции обновления скрипта" debug_step "Запуск функции обновления скрипта"
@@ -1757,6 +1753,11 @@ parse_command_line "$@"
deploy_require_root deploy_require_root
require_repo_url require_repo_url
load_ssh_monitor_perms_lib || true
if declare -F ssh_monitor_update_mark_begin >/dev/null 2>&1; then
ssh_monitor_update_mark_begin
fi
if [ "$DEPLOY_MODE" -eq 1 ]; then if [ "$DEPLOY_MODE" -eq 1 ]; then
printf '\n=== ssh-monitor: первичная установка (--deploy) ===\n' printf '\n=== ssh-monitor: первичная установка (--deploy) ===\n'
say_step "Репозиторий и файлы" say_step "Репозиторий и файлы"
+1 -1
View File
@@ -1 +1 @@
2.2.1-SAC 2.2.3-SAC