#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Лёгкий диагностический агент sysadminit.pro (Linux / macOS). Запуск: python3 agent.py --token <ТОКЕН> Токен берётся из личного кабинета (блок «Диагностический агент»). Адрес сервера можно переопределить: --url https://… или переменной SYSA_URL. """ import json import os import platform import re import socket import subprocess import sys import time from urllib import request as urlreq URL_DEFAULT = 'https://sysadminit.pro' def sh(args, timeout=15): try: r = subprocess.run(args, capture_output=True, text=True, timeout=timeout) return (r.stdout or '').strip() except Exception: return '' def parse_os_release(): d = {} try: for line in open('/etc/os-release', encoding='utf-8', errors='replace'): if '=' in line: k, v = line.rstrip('\n').split('=', 1) d[k] = v.strip('"') except Exception: pass return d def arg_value(flag): args = sys.argv[1:] if flag in args: i = args.index(flag) if i + 1 < len(args): return args[i + 1] return None def get_token(): t = arg_value('--token') or arg_value('-t') or os.environ.get('SYSA_TOKEN') if t: return t.strip() return input('Токен из личного кабинета sysadminit.pro: ').strip() def get_url(): u = arg_value('--url') or os.environ.get('SYSA_URL') or URL_DEFAULT return u.rstrip('/') def main(): token = get_token() if len(token) != 32: print('Ошибка: неверный токен (нужно 32 символа).') sys.exit(1) url = get_url() system = platform.system().lower() # linux | darwin hostname = socket.gethostname() arch = platform.machine() kernel = platform.release() cpu_name = '' cores = os.cpu_count() or 0 ram_gb = 0.0 gpu = '' disks = [] software = [] sensors_raw = '' smart_raw = '' network_raw = '' uptime = 0 if system == 'darwin': os_name = sh(['sw_vers', '-productName']) or 'macOS' os_version = sh(['sw_vers', '-productVersion']) or (platform.mac_ver()[0] or '') cpu_name = sh(['sysctl', '-n', 'machdep.cpu.brand_string']) try: ram_gb = round(int(sh(['sysctl', '-n', 'hw.memsize']) or 0) / 1e9, 2) except Exception: ram_gb = 0.0 gpu = '' for line in sh(['system_profiler', 'SPDisplaysDataType']).splitlines(): if 'Chipset Model:' in line: gpu = line.split('Chipset Model:', 1)[1].strip() break if 'Model:' in line: gpu = line.split('Model:', 1)[1].strip() disks = [l for l in sh(['bash', '-c', "diskutil list | awk '/0:/{print}'"]).splitlines() if l] network_raw = sh(['bash', '-c', 'ifconfig | grep -E "^[a-z]|inet "']) for d in ('/Applications', '/System/Applications'): try: software.extend(sorted(n for n in os.listdir(d) if n.endswith('.app'))) except Exception: pass boot = sh(['sysctl', '-n', 'kern.boottime']) m = re.search(r'sec = (\d+)', boot) if m: uptime = max(0, int(time.time()) - int(m.group(1))) else: rel = parse_os_release() os_name = rel.get('NAME') or 'Linux' os_version = rel.get('VERSION') or '' try: for line in open('/proc/cpuinfo', encoding='utf-8', errors='replace'): if line.startswith('model name'): cpu_name = line.split(':', 1)[1].strip() break except Exception: pass if not cpu_name: cpu_name = sh(['uname', '-m']) try: for line in open('/proc/meminfo', encoding='utf-8', errors='replace'): if line.startswith('MemTotal'): ram_gb = round(int(line.split()[1]) / 1024 / 1024, 2) break except Exception: pass try: for line in open('/proc/uptime', encoding='utf-8', errors='replace'): uptime = int(float(line.split()[0])) break except Exception: pass lspci = sh(['lspci']) for line in lspci.splitlines(): if re.search(r'vga|3d|display', line, re.I): gpu = line break disks = [l for l in sh(['lsblk', '-dno', 'NAME,SIZE,MODEL,SERIAL']).splitlines() if l] if sh(['which', 'dpkg-query']): software = sh(['dpkg-query', '-f', '${Package}\t${Version}\n', '-W']).splitlines() elif sh(['which', 'rpm']): software = sh(['rpm', '-qa', '--qf', '%{NAME}\t%{VERSION}-%{RELEASE}\n']).splitlines() software = software[:1000] sensors_raw = sh(['sensors']) smart_raw = sh(['smartctl', '--scan']) network_raw = sh(['ip', '-br', 'addr']) or sh(['ifconfig']) payload = { 'os': {'name': os_name, 'version': os_version, 'arch': arch}, 'hostname': hostname, 'kernel': kernel, 'uptime_seconds': uptime, 'cpu': {'name': cpu_name, 'cores': cores}, 'gpu': {'name': gpu} if gpu else {}, 'ram_gb': ram_gb, 'disks': disks, 'smart_raw': smart_raw, 'sensors_raw': sensors_raw, 'network_raw': network_raw, 'software': software, 'collected_at': time.strftime('%Y-%m-%dT%H:%M:%S%z'), } body = { 'token': token, 'platform': system, 'hostname': hostname, 'os_name': os_name, 'os_version': os_version, 'arch': arch, 'agent_version': '1.1', 'payload': payload, } print('Отправка отчёта в', url, '...') data = json.dumps(body, ensure_ascii=False).encode('utf-8') req = urlreq.Request( url + '/api.php?action=diagnostic_report', data=data, headers={ 'Content-Type': 'application/json; charset=utf-8', 'User-Agent': 'Mozilla/5.0 (compatible; sysadminit-agent/1.1)', 'Accept': 'application/json', }, method='POST', ) try: with urlreq.urlopen(req, timeout=60) as r: resp = json.loads(r.read().decode('utf-8')) except urlreq.HTTPError as e: try: detail = e.read().decode('utf-8', 'replace')[:500] except Exception: detail = '' print('Ошибка отправки: HTTP', e.code, detail) sys.exit(1) except Exception as e: print('Ошибка отправки:', e) sys.exit(1) if resp.get('ok'): print('Готово: отчёт принят (id', resp.get('id'), ')') else: print('Сервер:', resp.get('error')) sys.exit(1) if __name__ == '__main__': main()