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 →

Reset

6 posts tagged #скрипты: articles, how-tos, projects and jobs from the portal's IT professionals.

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

🌐 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:

Read more
Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up
Редакция КоммитРедакция портала
commit 052e692 · 15 days ago

🌐 Machine-translated from Russian. Show original

In this part:

What we will do

  1. Alerts: any script from previous parts sends a message to the chat—without a separate bot process.
  2. Bot with commands: /status checks ports, /certs — certificate deadlines; the bot responds only to "its own."
  3. Periodic checks inside the bot: once every 5 minutes — and a message only if something changes.

Creating a bot

  1. In Telegram, open @BotFather, command /newbot, enter the bot's name and login (ends with bot).
  2. BotFather will issue a token — this is the bot's password. Immediately put it in the .env as TG_BOT_TOKEN, don't send it anywhere. Leaked — /revoke to BotFather.
  3. Add the bot to the workgroup or message them privately.
  4. Learn chat_id: temporarily launch the bot from the section below and send a /start — it will show the chat ID.

Alerts from any script

No bot library is needed to send a message — one HTTP request to the Bot API is enough.

Read more
Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up
Редакция КоммитРедакция портала
commit fd1085c · 15 days ago

🌐 Machine-translated from Russian. Show original

In this part:

Availability checking: ping and ports

Ping shows that the host is alive, and checking the TCP port indicates that the service is running. For the admin, the second thing is more important: the server can ping, while the 1C or SQL service can be idle.

# src/pyreports/checks.py
import platform
import socket
import subprocess
from concurrent.futures import ThreadPoolExecutor


def ping(host: str, timeout_s: int = 1) -> bool:
    if platform.system() == "Windows":
        cmd = ["ping", "-n", "1", "-w", str(timeout_s * 1000), host]
    else:
        cmd = ["ping", "-c", "1", "-W", str(timeout_s), host]
    return subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0


def port_open(host: str, port: int, timeout_s: float = 2) -> bool:
    try:
        with socket.create_connection((host, port), timeout=timeout_s):
            return True
    except OSError:
        return False


TARGETS = [
    ("srv-1c.corp.local", 1541),    # менеджер кластера 1С
    ("srv-sql.corp.local", 5432),   # PostgreSQL
    ("dc01.corp.local", 636),       # LDAPS
    ("mail.company.kz", 587),       # SMTP
]


def check_all(targets=TARGETS) -> list[tuple[str, int, bool]]:
    with ThreadPoolExecutor(max_workers=20) as pool:
        results = pool.map(lambda t: (t[0], t[1], port_open(*t)), targets)
    return list(results)


if __name__ == "__main__":
    for host, port, ok in check_all():
        print(f"{'OK  ' if ok else 'FAIL'} {host}:{port}")
Read more
Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up
Редакция КоммитРедакция портала
commit 9d53ada · 15 days ago

🌐 Machine-translated from Russian. Show original

In this part:

requests or httpx

requestshttpx
Stylesynchronoussynchronous and asynchronous
HTTP/2noyes (packet httpx[http2])
Default timeoutno (can wait forever)5 seconds
Repeatsafter urllib3.Retryonly the connection repeat; the rest is your own code
Whereappears in a huge number of examples and librariesin modern projects, python-telegram-bot runs on top of it

Both libraries are good. In new scripts, httpx is more convenient: the same API, plus async when needed (the bot in part 5 is asynchronous).

uv add httpx

First request

An example with a real public API — what is the latest version of the project on GitHub. It's convenient to keep track of software updates you maintain.

Read more
Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up
Редакция КоммитРедакция портала
commit 9e4dd9b · 15 days ago

🌐 Machine-translated from Russian. Show original

In this part:

pathlib — pain-free paths

The pathlib module works the same on Windows and Linux, and paths can be written through direct slash even on Windows.

from datetime import datetime, timedelta
from pathlib import Path

base = Path("D:/exchange")          # на Linux, например, Path("/srv/exchange")
report = base / "out" / f"report_{datetime.now():%Y-%m-%d}.xlsx"
report.parent.mkdir(parents=True, exist_ok=True)

print(report.name, report.suffix, report.stem)
print(report.exists())

# все CSV в папке и подпапках
for f in base.rglob("*.csv"):
    print(f, f.stat().st_size)

Windows network folders also work: Path("//fileserver/exchange") — Python understands UNC paths with direct slashes.

Example: cleaning old files with a "trial run"

Any script it removes should first run in "show only" mode.

Read more
Comments 00 участников · 0 гостей🔒 Rate and discuss after signing up
Редакция КоммитРедакция портала
commit f4fc706 · 15 days ago

🌐 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.

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