# Exemplo de como integrar o MDM no CLIENTE_CORRIGIDO.py """ INSTRUÇÕES: 1. Copie CLIENT_MDM.py para a mesma pasta do CLIENTE_CORRIGIDO.py 2. Adicione este código no CLIENTE_CORRIGIDO.py 3. Recompile com PyInstaller """ # ============================================ # ADICIONAR NO INÍCIO DO ARQUIVO (imports) # ============================================ from CLIENT_MDM import run_mdm_polling, MDMExecutor from threading import Thread # ============================================ # ADICIONAR NA FUNÇÃO main(), APÓS device_id SER CONFIGURADO # ============================================ def main(): # ... código existente ... device_id = config.get('device_id') print(f"✅ NoIdle iniciado - Device ID: {device_id}") # ADICIONAR AQUI: Iniciar MDM polling print("🛡️ Iniciando módulo MDM...") def start_mdm(): """Função para rodar MDM em thread separada""" try: run_mdm_polling(API_URL, device_id, interval_seconds=60) except Exception as e: print(f"❌ Erro no MDM: {e}") # Iniciar thread do MDM mdm_thread = Thread(target=start_mdm, daemon=True, name="MDM-Thread") mdm_thread.start() print("✅ MDM ativo - Polling a cada 60 segundos") # ... resto do código existente ... # ============================================ # EXEMPLO COMPLETO DE USO # ============================================ def exemplo_uso_mdm(): """ Exemplo de como usar o MDM manualmente (para testes) """ # Criar executor MDM executor = MDMExecutor( api_url="https://admin.noidle.tech/api", device_id="DEV-TEST-123" ) # Exemplo 1: Buscar comandos pendentes print("Buscando comandos pendentes...") commands = executor.poll_commands() print(f"Encontrados {len(commands)} comandos") # Exemplo 2: Executar comandos for command in commands: print(f"\nExecutando: {command['policy_name']}") success = executor.execute_command(command) if success: print("✅ Comando executado com sucesso") else: print("❌ Falha ao executar comando") # Exemplo 3: Testar Windows Update manualmente print("\nTestando Windows Update...") result = executor.execute_windows_update({ 'reboot_if_required': True, 'reboot_delay_minutes': 30 }) print(f"Resultado: {result}") # ============================================ # ESTRUTURA FINAL DO CLIENTE_CORRIGIDO.py # ============================================ """ CLIENTE_CORRIGIDO.py (estrutura simplificada): import os import sys ... from CLIENT_MDM import run_mdm_polling # ADICIONAR from threading import Thread # ADICIONAR API_URL = "https://admin.noidle.tech/api" ... def main(): check_and_install() config = Config() if not config.has('device_id'): # Ativação... pass device_id = config.get('device_id') print(f"✅ NoIdle iniciado - Device ID: {device_id}") # ADICIONAR: Iniciar MDM def start_mdm(): run_mdm_polling(API_URL, device_id, interval_seconds=60) mdm_thread = Thread(target=start_mdm, daemon=True) mdm_thread.start() print("🛡️ MDM ativo") # Resto do código... on_logon() atexit.register(on_logoff) schedule.every(MONITOR_INTERVAL).seconds.do(monitor_activity) schedule.every(30).seconds.do(lambda: send_heartbeat(device_id)) # ...continua """ # ============================================ # TESTES UNITÁRIOS # ============================================ def test_mdm_executor(): """Testa executor MDM""" print("🧪 Testando MDM Executor...") # Mock de configuração test_config = { 'software_name': 'TestApp', 'script': 'Write-Host "Hello from MDM"', 'reboot_delay_minutes': 5 } executor = MDMExecutor( api_url="https://admin.noidle.tech/api", device_id="TEST-DEVICE" ) # Testar cada handler print("✅ MDM Executor inicializado") print(f"Handlers disponíveis: {list(executor.handlers.keys())}") # Simular comando test_command = { 'command_id': 999, 'policy_name': 'Test Policy', 'command_type': 'powershell_script', 'command_data': test_config } # NÃO executar de verdade, apenas validar estrutura print("✅ Estrutura de comando validada") # ============================================ # EXEMPLOS DE CONFIGURAÇÃO DE POLÍTICAS # ============================================ EXEMPLOS_POLITICAS = { 'windows_update': { 'name': 'Windows Update Forçado', 'type': 'windows_update', 'config': { 'action': 'force_check_and_install', 'reboot_if_required': True, 'reboot_delay_minutes': 30, 'include_optional': False } }, 'install_chrome': { 'name': 'Instalar Google Chrome', 'type': 'software_install', 'config': { 'software_name': 'Google Chrome', 'download_url': 'https://dl.google.com/chrome/install/latest/chrome_installer.exe', 'install_args': '/silent /install' } }, 'cleanup': { 'name': 'Limpeza de Sistema', 'type': 'cleanup', 'config': { 'clear_temp': True, 'clear_windows_temp': True, 'clear_browser_cache': True, 'clear_recycle_bin': True } }, 'custom_script': { 'name': 'Script Personalizado', 'type': 'powershell_script', 'config': { 'script': ''' # Seu script PowerShell aqui Get-Process | Where-Object {$_.CPU -gt 100} | Select-Object Name, CPU, Memory | Format-Table ''', 'run_as_admin': True, 'timeout_minutes': 10 } } } # ============================================ # INSTRUÇÕES DE BUILD # ============================================ """ PARA COMPILAR COM MDM: 1. Certifique-se que CLIENT_MDM.py está na mesma pasta 2. Adicione ao spec file (se usar): hiddenimports=['CLIENT_MDM', 'winreg', ...] 3. Compile: pyinstaller --onefile --windowed --name NoIdle CLIENTE_CORRIGIDO.py 4. Teste o executável: .\dist\NoIdle.exe --silent 5. Verifique logs: - Deve aparecer "🛡️ MDM ativo" - Deve fazer polling a cada 60 segundos 6. Teste com comando real: - Crie política no dashboard - Aplique ao dispositivo - Execute política - Verifique resultado """ if __name__ == '__main__': print("Este é um arquivo de exemplo/documentação") print("Copie o código relevante para CLIENTE_CORRIGIDO.py") print("\nVer SISTEMA_MDM.md para documentação completa")