| [640ed89] | 1 | #!/usr/bin/env python3
|
|---|
| 2 | """
|
|---|
| 3 | POPRAVEN CLIENT со фикс за Sysmon
|
|---|
| 4 | """
|
|---|
| 5 |
|
|---|
| 6 | import socket
|
|---|
| 7 | import os
|
|---|
| 8 | import platform
|
|---|
| 9 | import json
|
|---|
| 10 | import requests
|
|---|
| 11 | from datetime import datetime, timedelta
|
|---|
| 12 | import psutil
|
|---|
| 13 | import time
|
|---|
| 14 | import subprocess
|
|---|
| 15 | import re
|
|---|
| 16 | from collections import defaultdict
|
|---|
| 17 |
|
|---|
| 18 |
|
|---|
| 19 | class FixedSysmonCollector:
|
|---|
| 20 | """Симплифициран колектор што работи без инсталиран Sysmon"""
|
|---|
| 21 |
|
|---|
| 22 | def __init__(self):
|
|---|
| 23 | self.last_collection = None
|
|---|
| 24 |
|
|---|
| 25 | def collect_sysmon_events(self, limit=50):
|
|---|
| 26 | """Симулирај Sysmon настани од процеси и мрежа"""
|
|---|
| 27 | events = []
|
|---|
| 28 |
|
|---|
| 29 | try:
|
|---|
| 30 | # 1. Процес настани (Event ID 1 = Process Creation)
|
|---|
| 31 | for proc in psutil.process_iter(['pid', 'name', 'create_time', 'username']):
|
|---|
| 32 | try:
|
|---|
| 33 | pinfo = proc.info
|
|---|
| 34 | if pinfo['create_time']:
|
|---|
| 35 | create_time = datetime.fromtimestamp(pinfo['create_time'])
|
|---|
| 36 | # Додади само процеси креирани во последните 5 минути
|
|---|
| 37 | if not self.last_collection or create_time > self.last_collection:
|
|---|
| 38 | events.append({
|
|---|
| 39 | "event_id": 1,
|
|---|
| 40 | "event_type": "Process Creation",
|
|---|
| 41 | "message": f"Process created: {pinfo['name']} (PID: {pinfo['pid']}, User: {pinfo['username']})",
|
|---|
| 42 | "timestamp": create_time.isoformat(),
|
|---|
| 43 | "process_name": pinfo['name'],
|
|---|
| 44 | "pid": pinfo['pid'],
|
|---|
| 45 | "user": pinfo['username']
|
|---|
| 46 | })
|
|---|
| 47 | except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|---|
| 48 | continue
|
|---|
| 49 |
|
|---|
| 50 | if len(events) >= limit // 2:
|
|---|
| 51 | break
|
|---|
| 52 |
|
|---|
| 53 | # 2. Мрежни конекции (Event ID 3 = Network Connection)
|
|---|
| 54 | for conn in psutil.net_connections(kind='inet'):
|
|---|
| 55 | try:
|
|---|
| 56 | if conn.raddr and conn.status in ['ESTABLISHED', 'LISTEN']:
|
|---|
| 57 | proc = psutil.Process(conn.pid) if conn.pid else None
|
|---|
| 58 | events.append({
|
|---|
| 59 | "event_id": 3,
|
|---|
| 60 | "event_type": "Network Connection",
|
|---|
| 61 | "message": f"Network {conn.status}: {conn.laddr.ip if conn.laddr else 'N/A'}:{conn.laddr.port if conn.laddr else 'N/A'} -> {conn.raddr.ip}:{conn.raddr.port}",
|
|---|
| 62 | "timestamp": datetime.now().isoformat(),
|
|---|
| 63 | "local_address": f"{conn.laddr.ip}:{conn.laddr.port}" if conn.laddr else None,
|
|---|
| 64 | "remote_address": f"{conn.raddr.ip}:{conn.raddr.port}",
|
|---|
| 65 | "status": conn.status,
|
|---|
| 66 | "pid": conn.pid,
|
|---|
| 67 | "process_name": proc.name() if proc else "Unknown"
|
|---|
| 68 | })
|
|---|
| 69 | except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|---|
| 70 | continue
|
|---|
| 71 |
|
|---|
| 72 | if len(events) >= limit:
|
|---|
| 73 | break
|
|---|
| 74 |
|
|---|
| 75 | # 3. Системски перформанси настани
|
|---|
| 76 | cpu = psutil.cpu_percent(interval=0.1)
|
|---|
| 77 | if cpu > 80:
|
|---|
| 78 | events.append({
|
|---|
| 79 | "event_id": "PERF_HIGH_CPU",
|
|---|
| 80 | "event_type": "High CPU Usage",
|
|---|
| 81 | "message": f"High CPU usage detected: {cpu:.1f}%",
|
|---|
| 82 | "timestamp": datetime.now().isoformat(),
|
|---|
| 83 | "cpu_percent": cpu
|
|---|
| 84 | })
|
|---|
| 85 |
|
|---|
| 86 | ram = psutil.virtual_memory()
|
|---|
| 87 | if ram.percent > 85:
|
|---|
| 88 | events.append({
|
|---|
| 89 | "event_id": "PERF_HIGH_RAM",
|
|---|
| 90 | "event_type": "High Memory Usage",
|
|---|
| 91 | "message": f"High RAM usage: {ram.percent:.1f}%",
|
|---|
| 92 | "timestamp": datetime.now().isoformat(),
|
|---|
| 93 | "ram_percent": ram.percent
|
|---|
| 94 | })
|
|---|
| 95 |
|
|---|
| 96 | except Exception as e:
|
|---|
| 97 | print(f"FixedSysmon error: {e}")
|
|---|
| 98 |
|
|---|
| 99 | self.last_collection = datetime.now()
|
|---|
| 100 | return events
|
|---|
| 101 |
|
|---|
| 102 | def collect_network_connections_detailed(self):
|
|---|
| 103 | """Детални мрежни конекции"""
|
|---|
| 104 | connections = []
|
|---|
| 105 | try:
|
|---|
| 106 | for conn in psutil.net_connections(kind='inet'):
|
|---|
| 107 | try:
|
|---|
| 108 | proc = psutil.Process(conn.pid) if conn.pid else None
|
|---|
| 109 |
|
|---|
| 110 | conn_info = {
|
|---|
| 111 | "pid": conn.pid,
|
|---|
| 112 | "status": conn.status,
|
|---|
| 113 | "family": str(conn.family),
|
|---|
| 114 | "type": str(conn.type),
|
|---|
| 115 | "timestamp": datetime.now().isoformat()
|
|---|
| 116 | }
|
|---|
| 117 |
|
|---|
| 118 | if conn.laddr:
|
|---|
| 119 | conn_info["local_address"] = f"{conn.laddr.ip}:{conn.laddr.port}"
|
|---|
| 120 | conn_info["local_ip"] = conn.laddr.ip
|
|---|
| 121 | conn_info["local_port"] = conn.laddr.port
|
|---|
| 122 |
|
|---|
| 123 | if conn.raddr:
|
|---|
| 124 | conn_info["remote_address"] = f"{conn.raddr.ip}:{conn.raddr.port}"
|
|---|
| 125 | conn_info["remote_ip"] = conn.raddr.ip
|
|---|
| 126 | conn_info["remote_port"] = conn.raddr.port
|
|---|
| 127 |
|
|---|
| 128 | if proc:
|
|---|
| 129 | conn_info.update({
|
|---|
| 130 | "process_name": proc.name(),
|
|---|
| 131 | "process_cmdline": ' '.join(proc.cmdline()) if proc.cmdline() else None,
|
|---|
| 132 | "process_username": proc.username() if hasattr(proc, 'username') else None
|
|---|
| 133 | })
|
|---|
| 134 |
|
|---|
| 135 | connections.append(conn_info)
|
|---|
| 136 |
|
|---|
| 137 | except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|---|
| 138 | continue
|
|---|
| 139 |
|
|---|
| 140 | if len(connections) >= 30:
|
|---|
| 141 | break
|
|---|
| 142 |
|
|---|
| 143 | except Exception as e:
|
|---|
| 144 | print(f"Network connections error: {e}")
|
|---|
| 145 |
|
|---|
| 146 | return connections
|
|---|
| 147 |
|
|---|
| 148 | def collect_all_security_data(self):
|
|---|
| 149 | """Собери сите безбедносни податоци (очекуваниот метод!)"""
|
|---|
| 150 | return {
|
|---|
| 151 | "sysmon_events": self.collect_sysmon_events(limit=50),
|
|---|
| 152 | "network_connections": self.collect_network_connections_detailed(),
|
|---|
| 153 | "file_changes": [], # Празен лист, можеш да го имплементираш подоцна
|
|---|
| 154 | "collection_time": datetime.now().isoformat()
|
|---|
| 155 | }
|
|---|
| 156 |
|
|---|
| 157 |
|
|---|
| 158 | class EnhancedFixedClient:
|
|---|
| 159 | def __init__(self, server_ip="192.168.1.13", port=5555):
|
|---|
| 160 | self.server_ip = server_ip
|
|---|
| 161 | self.port = port
|
|---|
| 162 | self.computer_name = socket.gethostname()
|
|---|
| 163 | self.user = os.getlogin()
|
|---|
| 164 | self.sysmon_collector = FixedSysmonCollector() # Користи поправената верзија
|
|---|
| 165 |
|
|---|
| 166 | def get_detailed_info(self):
|
|---|
| 167 | """Собирај подробни податоци"""
|
|---|
| 168 | info = {
|
|---|
| 169 | "computer_name": self.computer_name,
|
|---|
| 170 | "user": self.user,
|
|---|
| 171 | "ip_address": socket.gethostbyname(self.computer_name),
|
|---|
| 172 | "os": f"{platform.system()} {platform.release()} {platform.version()}",
|
|---|
| 173 | "architecture": platform.architecture()[0],
|
|---|
| 174 | "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
|---|
| 175 | "is_sysmon_available": self._check_sysmon_installed()
|
|---|
| 176 | }
|
|---|
| 177 |
|
|---|
| 178 | info.update(self.get_performance_metrics())
|
|---|
| 179 | info.update(self.get_hardware_info())
|
|---|
| 180 |
|
|---|
| 181 | return info
|
|---|
| 182 |
|
|---|
| 183 | def _check_sysmon_installed(self):
|
|---|
| 184 | """Провери дали Sysmon е инсталиран"""
|
|---|
| 185 | try:
|
|---|
| 186 | if platform.system() == "Windows":
|
|---|
| 187 | result = subprocess.run(
|
|---|
| 188 | ["powershell", "-Command", "Get-Process -Name 'sysmon' -ErrorAction SilentlyContinue"],
|
|---|
| 189 | capture_output=True, text=True
|
|---|
| 190 | )
|
|---|
| 191 | return result.returncode == 0
|
|---|
| 192 | except:
|
|---|
| 193 | pass
|
|---|
| 194 | return False
|
|---|
| 195 |
|
|---|
| 196 | def get_performance_metrics(self):
|
|---|
| 197 | """Метрики за перформанси - ПОПРАВЕНО БЕЗ DEPRECATION WARNING"""
|
|---|
| 198 | try:
|
|---|
| 199 | cpu_percent = psutil.cpu_percent(interval=1)
|
|---|
| 200 | cpu_freq = psutil.cpu_freq()
|
|---|
| 201 |
|
|---|
| 202 | ram = psutil.virtual_memory()
|
|---|
| 203 | swap = psutil.swap_memory()
|
|---|
| 204 |
|
|---|
| 205 | disk = psutil.disk_usage("C:/" if platform.system() == "Windows" else "/")
|
|---|
| 206 |
|
|---|
| 207 | # ДОБАВИ TRY-EXCEPT за disk_io_counters
|
|---|
| 208 | disk_read_mb = 0
|
|---|
| 209 | disk_write_mb = 0
|
|---|
| 210 | try:
|
|---|
| 211 | disk_io = psutil.disk_io_counters()
|
|---|
| 212 | if disk_io:
|
|---|
| 213 | disk_read_mb = round(disk_io.read_bytes / (1024 ** 2), 2)
|
|---|
| 214 | disk_write_mb = round(disk_io.write_bytes / (1024 ** 2), 2)
|
|---|
| 215 | except:
|
|---|
| 216 | pass
|
|---|
| 217 |
|
|---|
| 218 | net_io = psutil.net_io_counters()
|
|---|
| 219 |
|
|---|
| 220 | return {
|
|---|
| 221 | "cpu_usage": cpu_percent,
|
|---|
| 222 | "cpu_cores": psutil.cpu_count(logical=True),
|
|---|
| 223 | "cpu_freq_current": cpu_freq.current if cpu_freq else 0,
|
|---|
| 224 | "ram_usage": ram.percent,
|
|---|
| 225 | "ram_total_gb": round(ram.total / (1024 ** 3), 2),
|
|---|
| 226 | "ram_used_gb": round(ram.used / (1024 ** 3), 2),
|
|---|
| 227 | "swap_usage": swap.percent if swap else 0,
|
|---|
| 228 | "disk_usage": disk.percent,
|
|---|
| 229 | "disk_total_gb": round(disk.total / (1024 ** 3), 2),
|
|---|
| 230 | "disk_used_gb": round(disk.used / (1024 ** 3), 2),
|
|---|
| 231 | "disk_read_mb": disk_read_mb,
|
|---|
| 232 | "disk_write_mb": disk_write_mb,
|
|---|
| 233 | "network_sent_mb": round(net_io.bytes_sent / (1024 ** 2), 2),
|
|---|
| 234 | "network_recv_mb": round(net_io.bytes_recv / (1024 ** 2), 2),
|
|---|
| 235 | "network_packets_sent": net_io.packets_sent,
|
|---|
| 236 | "network_packets_recv": net_io.packets_recv,
|
|---|
| 237 | "boot_time": datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"),
|
|---|
| 238 | "uptime_hours": round((datetime.now() - datetime.fromtimestamp(psutil.boot_time())).seconds / 3600, 2)
|
|---|
| 239 | }
|
|---|
| 240 | except Exception as e:
|
|---|
| 241 | print(f"Performance metrics error: {e}")
|
|---|
| 242 | return {}
|
|---|
| 243 |
|
|---|
| 244 | def get_hardware_info(self):
|
|---|
| 245 | """Хардвер информации"""
|
|---|
| 246 | try:
|
|---|
| 247 | partitions = []
|
|---|
| 248 | for partition in psutil.disk_partitions():
|
|---|
| 249 | try:
|
|---|
| 250 | usage = psutil.disk_usage(partition.mountpoint)
|
|---|
| 251 | partitions.append({
|
|---|
| 252 | "device": partition.device,
|
|---|
| 253 | "mountpoint": partition.mountpoint,
|
|---|
| 254 | "fstype": partition.fstype,
|
|---|
| 255 | "total_gb": round(usage.total / (1024 ** 3), 2),
|
|---|
| 256 | "used_gb": round(usage.used / (1024 ** 3), 2),
|
|---|
| 257 | "free_gb": round(usage.free / (1024 ** 3), 2),
|
|---|
| 258 | "percent_used": usage.percent
|
|---|
| 259 | })
|
|---|
| 260 | except:
|
|---|
| 261 | continue
|
|---|
| 262 |
|
|---|
| 263 | # Мрежни интерфејси
|
|---|
| 264 | net_if_addrs = psutil.net_if_addrs()
|
|---|
| 265 | interfaces = {}
|
|---|
| 266 | for interface, addrs in net_if_addrs.items():
|
|---|
| 267 | interfaces[interface] = [
|
|---|
| 268 | {
|
|---|
| 269 | "family": str(addr.family),
|
|---|
| 270 | "address": addr.address,
|
|---|
| 271 | "netmask": addr.netmask if hasattr(addr, 'netmask') else None
|
|---|
| 272 | }
|
|---|
| 273 | for addr in addrs if addr.address
|
|---|
| 274 | ]
|
|---|
| 275 |
|
|---|
| 276 | return {
|
|---|
| 277 | "cpu_physical_cores": psutil.cpu_count(logical=False),
|
|---|
| 278 | "cpu_logical_cores": psutil.cpu_count(logical=True),
|
|---|
| 279 | "disks": partitions,
|
|---|
| 280 | "network_interfaces": interfaces,
|
|---|
| 281 | "battery_percent": psutil.sensors_battery().percent if hasattr(psutil.sensors_battery(),
|
|---|
| 282 | 'percent') else None,
|
|---|
| 283 | "temperatures": self._get_temperatures()
|
|---|
| 284 | }
|
|---|
| 285 | except Exception as e:
|
|---|
| 286 | print(f"Hardware info error: {e}")
|
|---|
| 287 | return {}
|
|---|
| 288 |
|
|---|
| 289 | def _get_temperatures(self):
|
|---|
| 290 | """Добиј температури на системот"""
|
|---|
| 291 | try:
|
|---|
| 292 | temps = {}
|
|---|
| 293 | if hasattr(psutil, 'sensors_temperatures'):
|
|---|
| 294 | sensors = psutil.sensors_temperatures()
|
|---|
| 295 | for name, entries in sensors.items():
|
|---|
| 296 | if entries:
|
|---|
| 297 | temps[name] = entries[0].current
|
|---|
| 298 | return temps
|
|---|
| 299 | except:
|
|---|
| 300 | return {}
|
|---|
| 301 |
|
|---|
| 302 | def get_detailed_processes(self):
|
|---|
| 303 | """Детални информации за процесите - ПОПРАВЕНО БЕЗ DEPRECATION WARNING"""
|
|---|
| 304 | processes = []
|
|---|
| 305 | try:
|
|---|
| 306 | for proc in psutil.process_iter(['pid', 'name', 'username', 'cpu_percent',
|
|---|
| 307 | 'memory_percent', 'create_time', 'status']):
|
|---|
| 308 | try:
|
|---|
| 309 | pinfo = proc.info
|
|---|
| 310 |
|
|---|
| 311 | # КОРИСТИ psutil.Process() за да добиеш дополнителни информации
|
|---|
| 312 | with proc.oneshot():
|
|---|
| 313 | processes.append({
|
|---|
| 314 | "pid": pinfo['pid'],
|
|---|
| 315 | "name": pinfo['name'],
|
|---|
| 316 | "user": pinfo['username'],
|
|---|
| 317 | "cpu_percent": pinfo['cpu_percent'],
|
|---|
| 318 | "memory_mb": round(proc.memory_info().rss / (1024 ** 2), 2),
|
|---|
| 319 | "memory_percent": pinfo['memory_percent'],
|
|---|
| 320 | "create_time": datetime.fromtimestamp(pinfo['create_time']).strftime("%Y-%m-%d %H:%M:%S") if
|
|---|
| 321 | pinfo['create_time'] else None,
|
|---|
| 322 | "status": pinfo['status'],
|
|---|
| 323 | "exe": proc.exe() if hasattr(proc, 'exe') else None,
|
|---|
| 324 | "cmdline": ' '.join(proc.cmdline()) if hasattr(proc, 'cmdline') else None,
|
|---|
| 325 | "num_threads": proc.num_threads() if hasattr(proc, 'num_threads') else None,
|
|---|
| 326 | # НЕ КОРИСТИ proc.connections() - тоа е deprecated!
|
|---|
| 327 | "connections_count": 0 # Стави 0 или избриши го ова поле
|
|---|
| 328 | })
|
|---|
| 329 | except (psutil.NoSuchProcess, psutil.AccessDenied):
|
|---|
| 330 | continue
|
|---|
| 331 |
|
|---|
| 332 | if len(processes) >= 100:
|
|---|
| 333 | break
|
|---|
| 334 |
|
|---|
| 335 | except Exception as e:
|
|---|
| 336 | print(f"Process error: {e}")
|
|---|
| 337 |
|
|---|
| 338 | return processes
|
|---|
| 339 |
|
|---|
| 340 | def collect_and_send(self):
|
|---|
| 341 | """Собери и испрати сите податоци"""
|
|---|
| 342 | print(f"\n[{datetime.now().strftime('%H:%M:%S')}] 🔍 Собирање податоци...")
|
|---|
| 343 |
|
|---|
| 344 | # Собери сите податоци
|
|---|
| 345 | data = {
|
|---|
| 346 | "info": self.get_detailed_info(),
|
|---|
| 347 | "processes": self.get_detailed_processes(),
|
|---|
| 348 | "security_data": self.sysmon_collector.collect_all_security_data(), # ОВА СЕГА РАБОТИ!
|
|---|
| 349 | "collection_time": datetime.now().isoformat(),
|
|---|
| 350 | "client_version": "2.1_fixed"
|
|---|
| 351 | }
|
|---|
| 352 |
|
|---|
| 353 | # Прикажи основни информации
|
|---|
| 354 | info = data["info"]
|
|---|
| 355 | sec_data = data["security_data"]
|
|---|
| 356 |
|
|---|
| 357 | print(f" 💻 Компјутер: {info['computer_name']}")
|
|---|
| 358 | print(f" 👤 Корисник: {info['user']}")
|
|---|
| 359 | print(
|
|---|
| 360 | f" 📊 CPU: {info.get('cpu_usage', 0)}% | RAM: {info.get('ram_usage', 0)}% | Disk: {info.get('disk_usage', 0)}%")
|
|---|
| 361 | print(f" 🔄 Процеси: {len(data['processes'])}")
|
|---|
| 362 | print(f" 🛡️ Sysmon настани: {len(sec_data.get('sysmon_events', []))}")
|
|---|
| 363 | print(f" 🌐 Мрежни конекции: {len(sec_data.get('network_connections', []))}")
|
|---|
| 364 |
|
|---|
| 365 | # Испрати ги податоците
|
|---|
| 366 | try:
|
|---|
| 367 | response = requests.post(
|
|---|
| 368 | f"http://{self.server_ip}:{self.port}/receive",
|
|---|
| 369 | json=data,
|
|---|
| 370 | timeout=30
|
|---|
| 371 | )
|
|---|
| 372 |
|
|---|
| 373 | if response.status_code == 200:
|
|---|
| 374 | result = response.json()
|
|---|
| 375 | print(f" ✅ Податоците се успешно испратени!")
|
|---|
| 376 | if 'event_count' in result:
|
|---|
| 377 | print(f" 📝 Зачувани {result['event_count']} Sysmon настани")
|
|---|
| 378 | return True
|
|---|
| 379 | else:
|
|---|
| 380 | print(f" ❌ Грешка: {response.status_code}")
|
|---|
| 381 | return False
|
|---|
| 382 |
|
|---|
| 383 | except Exception as e:
|
|---|
| 384 | print(f" ❌ Проблем со серверот: {e}")
|
|---|
| 385 | return False
|
|---|
| 386 |
|
|---|
| 387 |
|
|---|
| 388 | def main():
|
|---|
| 389 | """Главна програма"""
|
|---|
| 390 | print("=" * 70)
|
|---|
| 391 | print("🖥️ FIXED LAN LOG COLLECTOR v2.1")
|
|---|
| 392 | print("=" * 70)
|
|---|
| 393 | print(f"Компјутер: {socket.gethostname()}")
|
|---|
| 394 | print(f"Корисник: {os.getlogin()}")
|
|---|
| 395 | print(f"IP: {socket.gethostbyname(socket.gethostname())}")
|
|---|
| 396 | print("=" * 70)
|
|---|
| 397 | print("Податоците ќе се собираат и испраќаат на секои 30 секунди.")
|
|---|
| 398 | print("Притисни Ctrl+C за да го прекинеш.")
|
|---|
| 399 | print("=" * 70)
|
|---|
| 400 |
|
|---|
| 401 | # Провери дали серверот е достапен
|
|---|
| 402 | server_ip = input("Внеси сервер IP (default 192.168.1.13): ").strip() or "192.168.1.13"
|
|---|
| 403 |
|
|---|
| 404 | client = EnhancedFixedClient(server_ip)
|
|---|
| 405 |
|
|---|
| 406 | # Тест конекција
|
|---|
| 407 | print(f"\n🔌 Тестирање на врска со серверот {server_ip}...")
|
|---|
| 408 | try:
|
|---|
| 409 | response = requests.get(f"http://{server_ip}:5555/ping", timeout=5)
|
|---|
| 410 | if response.status_code == 200:
|
|---|
| 411 | print(" ✅ Серверот е достапен!")
|
|---|
| 412 | else:
|
|---|
| 413 | print(f" ⚠️ Серверот одговори со: {response.status_code}")
|
|---|
| 414 | confirm = input(" Сакаш ли да продолжиш? (y/n): ").lower()
|
|---|
| 415 | if confirm != 'y':
|
|---|
| 416 | return
|
|---|
| 417 | except Exception as e:
|
|---|
| 418 | print(f" ❌ Не можам да се поврзам со серверот {server_ip}: {e}")
|
|---|
| 419 | confirm = input(" Сакаш ли да продолжиш? (y/n): ").lower()
|
|---|
| 420 | if confirm != 'y':
|
|---|
| 421 | return
|
|---|
| 422 |
|
|---|
| 423 | try:
|
|---|
| 424 | count = 1
|
|---|
| 425 | while True:
|
|---|
| 426 | print(f"\n📤 Трансмисија #{count}")
|
|---|
| 427 |
|
|---|
| 428 | success = client.collect_and_send()
|
|---|
| 429 |
|
|---|
| 430 | count += 1
|
|---|
| 431 | print(f"\n⏳ Чекам 30 секунди до следната трансмисија...")
|
|---|
| 432 |
|
|---|
| 433 | # Countdown
|
|---|
| 434 | for i in range(30, 0, -1):
|
|---|
| 435 | if i % 10 == 0 or i <= 5:
|
|---|
| 436 | print(f"\r {i} секунди остануваат...", end="")
|
|---|
| 437 | time.sleep(1)
|
|---|
| 438 | print("\r" + " " * 40 + "\r", end="")
|
|---|
| 439 |
|
|---|
| 440 | except KeyboardInterrupt:
|
|---|
| 441 | print("\n\n🛑 Програмата е зајчана.")
|
|---|
| 442 | print(f"📊 Dashboard: http://{server_ip}:5555/")
|
|---|
| 443 |
|
|---|
| 444 |
|
|---|
| 445 | if __name__ == "__main__":
|
|---|
| 446 | try:
|
|---|
| 447 | import psutil
|
|---|
| 448 | import requests
|
|---|
| 449 | except ImportError:
|
|---|
| 450 | print("Инсталирај ги модулите:")
|
|---|
| 451 | print("pip install psutil requests")
|
|---|
| 452 | input("Притисни ENTER за излез...")
|
|---|
| 453 | exit(1)
|
|---|
| 454 |
|
|---|
| 455 | main() |
|---|