
Python for Automation, Part 6: Logging, Testing, Packaging, and Secure Launch as a Service
🌐 Machine-translated from Russian. Show original
In this part:
Logging instead of print#
print good for debugging, but production requires time, level, message source, and file rotation. Configure once at the entry point:
# src/pyreports/logs.py
import logging
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path
def setup_logging(name: str, log_dir: str | None = None, level: int = logging.INFO) -> None:
fmt = logging.Formatter("%(asctime)s %(levelname)-7s %(name)s: %(message)s")
root = logging.getLogger()
root.setLevel(level)
console = logging.StreamHandler(sys.stdout) # под systemd это уйдет в journald
console.setFormatter(fmt)
root.addHandler(console)
if log_dir: # на Windows и в cron — файл с ротацией
Path(log_dir).mkdir(parents=True, exist_ok=True)
fh = RotatingFileHandler(Path(log_dir) / f"{name}.log", maxBytes=5_000_000, backupCount=10, encoding="utf-8")
fh.setFormatter(fmt)
root.addHandler(fh)
logging.getLogger("httpx").setLevel(logging.WARNING) # не пишем URL с токенами
logging.getLogger("paramiko").setLevel(logging.WARNING)
Rules:
log.info("Обработано %d строк", n)— parameters separated by commas, not an f-string: the string will only be added if the message is actually written.log.exception("...")inside theexceptwill record a full traceback.- Never log passwords, tokens, full authorization headers, or personal data.
- Systemd does not require its own file:
journalctl -u имя-службыalready provides time, rotation, and search.
Tests on pytest#
Even for scripts, it's worth covering "pure" logic with tests: parsing CSV, calculations, message generation. We substitute network and SSH in tests.
uv add --dev pytest
# tests/test_checks.py
import socket
from pyreports import checks
def test_port_open_on_local_listener():
srv = socket.socket()
srv.bind(("127.0.0.1", 0)) # свободный порт
srv.listen()
port = srv.getsockname()[1]
try:
assert checks.port_open("127.0.0.1", port) is True
finally:
srv.close()
def test_port_closed():
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close() # порт заведомо никто не слушает
assert checks.port_open("127.0.0.1", port, timeout_s=0.5) is False
def test_check_all_uses_port_open(monkeypatch):
monkeypatch.setattr(checks, "port_open", lambda host, port: host == "up")
assert checks.check_all([("up", 1), ("down", 2)]) == [("up", 1, True), ("down", 2, False)]
# tests/test_cleanup.py — функция cleanup из части 2, вынесенная в src/pyreports/cleanup.py
import os
import time
from pyreports.cleanup import cleanup
def test_cleanup_dry_run_keeps_files(tmp_path):
old = tmp_path / "old.log"
old.write_text("x")
past = time.time() - 40 * 86400
os.utime(old, (past, past))
assert cleanup(tmp_path, days=30, pattern="*.log", dry_run=True) == 1
assert old.exists() # пробный запуск ничего не удалил
uv run pytest -q
Code quality: ruff#
Ruff — Linter and Formatter in one, replacing Flake8, Isort, and Black.
uv add --dev ruff
uv run ruff check . # ошибки и подозрительные места
uv run ruff check --fix . # исправить то, что можно автоматически
uv run ruff format . # единое форматирование
# pyproject.toml
[tool.ruff]
line-length = 120
target-version = "py313"
[tool.ruff.lint]
select = ["E", "F", "W", "I", "B", "UP", "S"] # S — проверки безопасности (bandit)
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"] # assert в тестах — норма
Group rules S catch, for example, subprocess with shell=True, verify=False and passwords in the code.
Packaging: commands instead of "python -m"#
In the pyproject.toml of the project created uv init --package, add entry points:
[project]
name = "pyreports"
version = "0.3.0"
requires-python = ">=3.13"
dependencies = [
"httpx>=0.28",
"openpyxl>=3.1",
"paramiko>=5.1",
"python-dotenv>=1.2",
"python-telegram-bot[job-queue]>=22.8",
]
[project.scripts]
pyreports-daily = "pyreports.daily:main"
pyreports-bot = "pyreports.bot:main"
[dependency-groups]
dev = ["pytest>=9", "ruff>=0.17"]
The block [build-system] uv init --package creates itself — do not change it without a reason.
uv sync # после изменения pyproject.toml
uv run pyreports-daily # команда появилась в .venv
uv build # wheel и sdist в папке dist/
Delivery options to the server:
| Method | When |
|---|---|
git clone + uv sync --locked | the easiest, with access to Git and PyPI |
wheel of dist/ + uv pip install in venv | server without Git |
uv tool install ./dist/pyreports-0.3.0-py3-none-any.whl | a single-user utility, commands go into PATH |
| Docker image | already has a Docker infrastructure — see the "Docker and CI/CD from Scratch" series |
Server without internet: on a machine with access run uv export --no-dev --no-hashes --format requirements-txt > requirements.txt and python -m pip download -r requirements.txt -d wheels/, move the wheels/ folder, and install venv: python -m pip install --no-index --find-links wheels/ -r requirements.txton the server. The platform and version of Python on both machines must match.
Bot as a Linux service (systemd)#
# /etc/systemd/system/pyreports-bot.service
[Unit]
Description=Telegram-бот pyreports
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pyreports
Group=pyreports
WorkingDirectory=/opt/pyreports
EnvironmentFile=/etc/pyreports.env
ExecStart=/opt/pyreports/.venv/bin/pyreports-bot
Restart=on-failure
RestartSec=10
# ограничения: процесс не получит лишних прав
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/opt/pyreports/state
CapabilityBoundingSet=
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now pyreports-bot
systemctl status pyreports-bot
journalctl -u pyreports-bot -f
systemd-analyze security pyreports-bot # оценка, насколько служба изолирована
ProtectSystem=strictmakes the entire file system read-only exceptReadWritePaths. If the script needs to write reports, add a folder there.Restart=on-failurewill pick up the bot after falling;RestartSecwon't let it "fight" in the loop.pinginside the service withRestrictAddressFamiliesand without privileges may not work — use TCP ports for checks.
Bot as a Windows task#
On Windows, the easiest way to run the bot is through the Task Scheduler at system startup with automatic restart:
$dir = "C:\Scripts\pyreports"
$action = New-ScheduledTaskAction -Execute "$dir\.venv\Scripts\pyreports-bot.exe" -WorkingDirectory $dir
$trigger = New-ScheduledTaskTrigger -AtStartup
$settings = New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable
Register-ScheduledTask -TaskName "pyreports-bot" -Action $action -Trigger $trigger -Settings $settings -User "CORP\svc-reports" -Password (Read-Host "Пароль svc-reports")
-ExecutionTimeLimit ([TimeSpan]::Zero)— no time limit, otherwise the Scheduler will stop the bot after 72 hours (default value).- Variables (
TG_BOT_TOKENand others) are.envin the project folder, with NTFS permissions only for service accounts and administrators. - If you need a full-fledged Windows service, wrappers like WinSW or NSSM are used — these are third-party utilities; check the source and version before installation.
Safe Launch Checklist#
- Secrets only in the environment or protected file; in Git —
.env.examplewithout values - Separate service account with minimal privileges (on Windows — gMSA if possible)
- Timeouts for all network operations, replays — only for temporary errors
- SSL verification enabled, corporate CA explicitly connected
- SSH — keys and
RejectPolicy, AD — LDAPS only - Dangerous actions — with trial mode and log
- Logs without passwords and tokens, errors — in Telegram
- The return code reflects the result, monitoring tracks the job
- Dependencies are recorded in
uv.lock, updated consciously:uv lock --upgrade→ tests → layout
Series Summary#
| Part | What can you do |
|---|---|
| 1 | install Python and uv, keep the project in order, run on schedule |
| 2 | working with files, CSV, and Excel, sending reports, |
| 3 | to go to APIs with timeouts, replays, and safe secrets |
| 4 | checking servers, working via SSH and WinRM, reading AD |
| 5 | send alerts and receive commands on Telegram |
| 6 | log, test, package, and run as a |
💬 What routine have you already automated in Python? Share the script in the comments — no passwords or internal addresses 🙂
🎉 Series completed. Return to contents.
Comments · 0
No comments yet.Sign in to comment, rate and see all comments.