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 fd1085c · 15 days ago

Python for automation, part 4: ping and ports, SSH via paramiko, PowerShell and WinRM, Active Directory via ldap3

🌐 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}")
  • Arguments subprocess pass as a list, without shell=True — otherwise, the hostname from the file or bot won't be able to "add" something of its own to the command.
  • ThreadPoolExecutor checks 20 addresses in parallel: a hundred ports in seconds.

SSL certificate validity period#

import socket
import ssl
import time


def cert_days_left(host: str, port: int = 443) -> int:
    ctx = ssl.create_default_context()
    with socket.create_connection((host, port), timeout=5) as sock:
        with ctx.wrap_socket(sock, server_hostname=host) as tls:
            cert = tls.getpeercert()
    expires = ssl.cert_time_to_seconds(cert["notAfter"])
    return int((expires - time.time()) // 86400)


for site in ["itgov.kz", "www.python.org"]:
    print(site, cert_days_left(site), "дн.")

If the certificate is already invalid or signed by an unknown center, wrap_socket will issue a ssl.SSLCertVerificationError — this is also a reason for notification.

SSH to Linux servers: paramiko#

uv add paramiko
import os
from pathlib import Path

import paramiko


def run_ssh(host: str, command: str, user: str = "monitor") -> tuple[int, str, str]:
    client = paramiko.SSHClient()
    client.load_system_host_keys()                            # ~/.ssh/known_hosts
    client.set_missing_host_key_policy(paramiko.RejectPolicy())  # незнакомый ключ хоста — отказ
    try:
        client.connect(
            host,
            username=user,
            key_filename=str(Path.home() / ".ssh" / "id_ed25519"),
            timeout=10,
        )
        _, stdout, stderr = client.exec_command(command, timeout=60)
        out = stdout.read().decode("utf-8", errors="replace")   # сначала читаем вывод,
        err = stderr.read().decode("utf-8", errors="replace")
        code = stdout.channel.recv_exit_status()                 # потом код возврата
        return code, out, err
    finally:
        client.close()


for host in ["srv-web01", "srv-web02", "srv-db01"]:
    code, out, err = run_ssh(host, "df -h --output=target,pcent / /var | tail -n +2")
    print(f"== {host} (код {code})")
    print(out or err)

Safety and details:

  • Only keys, not passwords. An individual user (monitor) with minimal permissions; if sudo is needed — allow specific commands in Sudoers.
  • RejectPolicy, not AutoAddPolicy: auto-adding the host key disables server spoofing protection. Add keys in advance with the ssh-keyscan host >> ~/.ssh/known_hosts command and reconcile fingerprints.
  • Paramiko 5.0 removed outdated algorithms: ssh-rsa signing with SHA-1, key exchange to SHA-1, and GSSAPI support. Old switches and ancient servers may stop connecting — it is better to update them than to keep the old library. DSA keys have not been supported since version 4.0.
  • Do not build a command from user input by concatenation. If the file name came from outside — shlex.quote(name).

For bulk configuration operations (deploying a package to 50 servers), Ansible is better suited — it is written in Python and uses SSH. A Python script is good for gathering information and non-standard logic.

Windows: PowerShell from Python#

Locally — via subprocess#

import json
import subprocess


def powershell_json(script: str) -> list[dict]:
    full = "[Console]::OutputEncoding = [Text.Encoding]::UTF8; " + script + " | ConvertTo-Json -Depth 3"
    r = subprocess.run(
        ["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", full],
        capture_output=True, text=True, encoding="utf-8", timeout=120,
    )
    if r.returncode != 0:
        raise RuntimeError(r.stderr.strip())
    data = json.loads(r.stdout or "[]")
    return data if isinstance(data, list) else [data]     # один объект PowerShell отдает не списком


services = powershell_json(
    "Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' } | "
    "Select-Object Name, DisplayName, @{n='Status'; e={ $_.Status.ToString() }}"
)
for s in services:
    print(s["Name"], s["DisplayName"], s["Status"])

Techniques:

  • ConvertTo-Json on the PowerShell side and json.loads in Python is much more reliable than parsing a text table.
  • [Console]::OutputEncoding = UTF8 and encoding="utf-8" — otherwise, Cyrillic in service names will turn into question marks.
  • Convert enumerations (service status) to a string after .ToString(), otherwise Windows PowerShell 5.1 will return a number.
  • If PowerShell 7 is installed, call pwsh.exe instead of powershell.exe.

Remote — via WinRM (pywinrm)#

On target servers, WinRM (Enable-PSRemoting, usually configured by Group Policy in the domain), port 5985 (HTTP), or 5986 (HTTPS) must be enabled.

uv add pywinrm
import json

import winrm

from pyreports.config import need

session = winrm.Session(
    "srv-1c.corp.local",
    auth=(need("WINRM_USER"), need("WINRM_PASSWORD")),     # например, CORP\svc-monitor
    transport="ntlm",
)

ps = (
    "Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | "
    "Select-Object DeviceID, @{n='FreeGB'; e={ [math]::Round($_.FreeSpace / 1GB, 1) }}, "
    "@{n='SizeGB'; e={ [math]::Round($_.Size / 1GB, 1) }} | ConvertTo-Json"
)
r = session.run_ps(ps)
if r.status_code != 0:
    raise RuntimeError(r.std_err.decode("utf-8", errors="replace"))
disks = json.loads(r.std_out)
disks = disks if isinstance(disks, list) else [disks]
for d in disks:
    print(d["DeviceID"], f"{d['FreeGB']} из {d['SizeGB']} ГБ свободно")
  • Transport ntlm over HTTP encrypts WinRM messages. For production, HTTPS (5986) with a certificate or Kerberos (transport="kerberos", an additional package and configured Kerberos on the machine with script are needed).
  • The account is a service account, with rights only for what is needed (the "Remote Management Users" group and rights for specific objects), not the domain administrator.

Active Directory via ldap3#

Typical tasks: find inactive accounts, unload group compositions, check whose password hasn't changed. The ldap3 library is written in pure Python and works on Windows and Linux.

i️ The latest release of ldap3 is 2.9.1 (2021). The library is stable and widely used but not evolving; keep an eye out for this when Python updates.

uv add ldap3

Connection — LDAPS only#

Do not use simple authorization (login and password) via regular LDAP on port 389: the password will appear plaintext. Connect to port 636 with controller certificate checking.

import ssl

from ldap3 import Connection, Server, Tls

from pyreports.config import need

tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file="certs/corp-root-ca.pem")
server = Server("dc01.corp.local", port=636, use_ssl=True, tls=tls)
conn = Connection(
    server,
    user=need("AD_USER"),            # svc-ldap-read@corp.local — в формате UPN
    password=need("AD_PASSWORD"),
    auto_bind=True,
    read_only=True,
)
print(conn.extend.standard.who_am_i())

To read AD, a regular domain account without privileges is sufficient — use a separate service account.

Inactive users for 90 days#

from datetime import datetime, timedelta, timezone

from ldap3 import SUBTREE

BASE = "DC=corp,DC=local"


def to_filetime(dt: datetime) -> int:
    """AD хранит время как число 100-наносекундных интервалов с 1601-01-01."""
    epoch = datetime(1601, 1, 1, tzinfo=timezone.utc)
    return int((dt - epoch).total_seconds() * 10_000_000)


border = to_filetime(datetime.now(timezone.utc) - timedelta(days=90))
flt = (
    "(&(objectCategory=person)(objectClass=user)"
    "(!(userAccountControl:1.2.840.113556.1.4.803:=2))"   # не отключенные
    f"(lastLogonTimestamp<={border}))"
)

entries = conn.extend.standard.paged_search(
    search_base=BASE,
    search_filter=flt,
    search_scope=SUBTREE,
    attributes=["sAMAccountName", "displayName", "lastLogonTimestamp", "department"],
    paged_size=500,
    generator=True,
)

rows = []
for e in entries:
    if e.get("type") != "searchResEntry":
        continue
    a = e["attributes"]
    rows.append({
        "login": a["sAMAccountName"],
        "name": a.get("displayName") or "",
        "department": a.get("department") or "",
        "last_logon": a.get("lastLogonTimestamp"),
    })

for r in sorted(rows, key=lambda r: r["last_logon"]):
    print(f"{r['login']:20} {r['last_logon']:%d.%m.%Y}  {r['name']}")
  • paged_search circumvents the AD limit of 1000 objects per response.
  • lastLogonTimestamp replicates between controllers with a delay of up to two weeks — this is fine for searching for "inactive 90 days," but not suitable for "who logged in yesterday."
  • Users who have never logged in will not be found by this filter: they have no attribute. Add a separate search (!(lastLogonTimestamp=*)) along with whenCreated.
  • ldap3 itself converts AD dates into datetimebecause it reads the schema when connected.

The result is easy to save in Excel with the make_report function from Python for automation, part 2: files, CSV, Excel, and report by mail

group_dn = "CN=VPN-Users,OU=Groups,DC=corp,DC=local"
conn.search(
    BASE,
    f"(&(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:={group_dn}))",   # правило LDAP_MATCHING_RULE_IN_CHAIN
    attributes=["sAMAccountName", "displayName"],
)
for e in conn.entries:
    print(e.sAMAccountName, e.displayName)

⚠️ Scripts that modify AD (disable accounts, move through the OU) should be run first in "show only" mode, with a log of all changes and from the account with delegated rights only to the required OUs.

Next — Telegram bot for alerts and commands: Python for automation, part 5: Telegram bot for alerts and simple commands.

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

Comments · 0

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