Guest mode. You can read posts without signing up. Comments, ratings, job contacts and your own posts open after you sign up and accept the rules. What is Kommit →

Редакция КоммитРедакция портала
commit f4fc706 · 15 days ago

Python for Automation, Part 1: Installation, UV, Project Structure, and Scheduled Launch

🌐 Machine-translated from Russian. Show original

In this part:

Why an admin and analyst needs Python#

PowerShell and bash are great for short commands. Python wins when the script starts growing: you need to read Excel, go to the API, compile a report, send it to Telegram, and work equally on Windows and Linux. Python has a huge standard library and ready-made packages for almost any system: Excel, SSH, LDAP, mail, databases, cloud.

Typical tasks this series will cover:

  • daily report from CSV or database in Excel and mailing;
  • checking the availability of servers, ports, and SSL certificate expirations;
  • unloading inactive accounts from Active Directory;
  • collecting information from a dozen servers via SSH or WinRM;
  • A Telegram bot that sends alerts and responds to commands /status.

Which version to take#

As of November 2026, the last stable branch is Python 3.15; the previous 3.14 also receives fixes, and 3.13 receives only security fixes. Each branch is supported for 5 years.

A practical rule: for working scripts, take the penultimate branch (3.14) if any library does not yet support the latest one. Example at the time of verification: the metadata of aiogram 3.31 indicates requires_python <3.15. Most packages in this series (requests, httpx, openpyxl, pandas, paramiko, python-telegram-bot) also work on 3.15. Python 3.10 and earlier are already out of support, so do not start new projects on them.

Where to watch: python.org/downloads — a table of branches with support periods.

Installation on Windows#

With Python 3.14, the recommended method is Python install manager (from python.org or from the Microsoft Store). The classic full installer has been declared obsolete and will not be released for 3.16.

# установить менеджер через winget (ID пакета из документации python.org)
winget install 9NQ7512CXL7T -e --accept-package-agreements --disable-interactivity

py install 3.14        # поставить нужную версию
py list                # что установлено
py -V:3.14 --version   # запустить конкретную версию

Documentation: docs.python.org — Using Python on Windows.

Installation on Linux#

In Ubuntu 24.04, system Python is 3.12. Do not touch it or install packages through sudo pip: apt and OS utilities depend on system Python. For your scripts, use a separate version via UV (below) or a virtual environment.

UV — one tool instead of pip, venv, and pyenv#

uv from Astral installs Python versions, creates environments, installs packages, and commits their versions to a lock file. Works very fast and equally on Windows and Linux.

# Windows
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# или
winget install --id=astral-sh.uv -e
# Linux / macOS
curl -LsSf https://astral.sh/uv/install.sh | sh
uv --version

New project#

uv python install 3.14          # uv сам скачает нужный Python
uv init --package pyreports     # проект с пакетом в src/
cd pyreports
uv python pin 3.14              # версия фиксируется в .python-version
uv add httpx openpyxl python-dotenv
uv add --dev pytest ruff
uv run python -c "import httpx; print(httpx.__version__)"

uv add writes the dependency to pyproject.toml and exact versions to uv.lock. On another computer or server, it is enough to:

uv sync --locked     # создаст .venv и поставит ровно те версии, что в uv.lock

If uv is not allowed: venv + pip#

In some companies, only the standard set is allowed. Then — the built-in module venv:

python3 -m venv .venv
source .venv/bin/activate              # Linux
# .venv\Scripts\Activate.ps1          # Windows PowerShell
python -m pip install --upgrade pip
python -m pip install httpx openpyxl python-dotenv
python -m pip freeze > requirements.txt

On the server: python -m pip install -r requirements.txt. The downside compared to uv is that there is no proper lock file with hashes, and the Python version must be set separately.

Project structure#

pyreports/
├── pyproject.toml        # зависимости и настройки инструментов
├── uv.lock               # точные версии пакетов (в Git)
├── .python-version
├── .env.example          # пример настроек БЕЗ реальных значений (в Git)
├── .env                  # реальные настройки и секреты (НЕ в Git)
├── .gitignore
├── src/pyreports/
│   ├── __init__.py
│   ├── config.py         # чтение настроек
│   ├── daily.py          # скрипт ежедневного отчета
│   └── checks.py         # проверки серверов
└── tests/
    └── test_checks.py

.gitignore — minimum:

.venv/
__pycache__/
.env
*.log
out/

Settings and secrets — only from the environment#

Passwords, tokens, and API keys are never written into the code. The code will go to Git, chat, flash drive — and with it the password. We read from environmental variables, and for convenience locally — from the .envfile:

# src/pyreports/config.py
import os

from dotenv import load_dotenv

load_dotenv()  # читает .env, если он есть; уже заданные переменные окружения не перезаписывает


def need(name: str) -> str:
    """Обязательная настройка: если не задана — падаем сразу и понятно."""
    value = os.environ.get(name)
    if not value:
        raise RuntimeError(f"Не задана переменная окружения {name}")
    return value


def opt(name: str, default: str) -> str:
    return os.environ.get(name, default)
# .env.example — копируем в .env и заполняем
SMTP_HOST=mail.company.local
SMTP_USER=reports@company.kz
SMTP_PASSWORD=
TG_BOT_TOKEN=
TG_CHAT_ID=

.env rights on Linux: chmod 600 .env, owner — the user from whom the script is run.

Entry point#

# src/pyreports/daily.py
import logging
import sys

log = logging.getLogger("pyreports.daily")


def main() -> int:
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
    log.info("Отчет запущен")
    # ... работа ...
    log.info("Отчет готов")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Launch: uv run python -m pyreports.daily. Return code 0 — success, any other — error: this is seen by scheduler, systemd, and monitoring.

Scheduled launch#

On the server, it's most convenient to perform uv sync --lockedjust once, and in the schedule to call Python directly from the .venv project — this way, uv is not needed in PATH at the service account.

⚠️ uv by default places Python in the current user's profile. If the script will run from another account, deploy the project on its behalf or set a shared directory: variable UV_PYTHON_INSTALL_DIR (for example, /opt/uv/python).

Windows: Task Scheduler#

$dir = "C:\Scripts\pyreports"
$action = New-ScheduledTaskAction -Execute "$dir\.venv\Scripts\python.exe" -Argument "-m pyreports.daily" -WorkingDirectory $dir
$trigger = New-ScheduledTaskTrigger -Daily -At 08:00
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Hours 1)
Register-ScheduledTask -TaskPath "\Reports\" -TaskName "pyreports-daily" -Action $action -Trigger $trigger -Settings $settings -User "CORP\svc-reports" -Password (Read-Host "Пароль svc-reports")
  • Run from a separate service account with minimal permissions, not from a domain administrator. Even better — gMSA: password changes automatically.
  • -WorkingDirectory is mandatory; otherwise, relative paths and .env will be sought in C:\Windows\System32.
  • Enable the launch history in the Scheduler: "Enable all task logs."

Linux: cron#

crontab -e
# будни, 08:00
0 8 * * 1-5 cd /opt/pyreports && /opt/pyreports/.venv/bin/python -m pyreports.daily >> /var/log/pyreports/daily.log 2>&1

Cron pitfalls: minimum PATH, no variables from your profile, the % character in the line needs to be shielded. Therefore, paths are only absolute.

Systemd timers provide a log in journalctl, protection against parallel startup, and a catch-up startup if the server was shut down.

# /etc/systemd/system/pyreports-daily.service
[Unit]
Description=Ежедневный отчет pyreports

[Service]
Type=oneshot
User=pyreports
WorkingDirectory=/opt/pyreports
EnvironmentFile=/etc/pyreports.env
ExecStart=/opt/pyreports/.venv/bin/python -m pyreports.daily
# /etc/systemd/system/pyreports-daily.timer
[Unit]
Description=Расписание pyreports-daily

[Timer]
OnCalendar=Mon..Fri 08:00
Persistent=true
RandomizedDelaySec=2m

[Install]
WantedBy=timers.target
sudo useradd --system --home /opt/pyreports --shell /usr/sbin/nologin pyreports
sudo install -m 600 -o root -g root /dev/null /etc/pyreports.env   # секреты — сюда
sudo systemctl daemon-reload
sudo systemctl enable --now pyreports-daily.timer
systemctl list-timers pyreports-daily.timer
sudo systemctl start pyreports-daily.service        # запустить вручную для проверки
journalctl -u pyreports-daily.service -n 50

EnvironmentFile reads systemd from root, so the file may belong to root with 600 rights — the service user will only get variables but will not be able to read the file.

Summary of the part#

  • Python 3.14 (or 3.15) via install manager or UV, system Python is not touched
  • A project with pyproject.toml and uv.lock in Git, .env — none
  • Secrets — from environmental variables
  • Scheduled start from official accounting, return code reflects result

Next — files, Excel, and reports by mail: Python for automation, part 2: files, CSV, Excel, and mail reports.

Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up

Comments · 0

No comments yet.Sign in to comment, rate and see all comments.