ElectroNeek Documentation

Guias práticos: Bot Runner


Registro de logs

Introdução

O ElectroNeek Bot Runner oferece registro automático de logs. O arquivo de log automático é a fonte de informação mais importante que pode ser obtida e enviada à equipe de suporte para resolver um determinado problema. Ele contém todas as informações sobre as especificações da máquina, a versão do Bot Runner e de seus componentes, além de cada etapa do fluxo de trabalho. Por isso, é o arquivo de log mais detalhado criado automaticamente.

O arquivo tem uma estrutura definida:

  1. Informações do ambiente (versão do sistema operacional, versões dos componentes etc.).
  2. Informações que descrevem cada etapa do bot. As etapas de início e fim da execução do bot também são registradas.

As informações são exibidas no formato “Horário da mensagem de log - JSON”, por exemplo:

16:26:46.328 {"programs":[{"program":"InternetExplorer","version":"11.789.19041.0"},

{"program":"Chrome","version":"91.0.4472.124"},

{"program":"1C"},{"program":"ElectroNeek Studio","version":"5.6.11.0"},

{"program":"ElectroNeek Robot","version":"5.6.11.0"},

{"program":"msedgedriver.exe","version":"79.0.313.0"}],"windows":{"caption":" Windows 10 Pro","version":"10.0.19042","csd_version":0,"os_architecture":"64-bit"},

"cpu":{"name":"AMD Ryzen 7 3700U with Radeon Vega Mobile Gfx","number_of_cores":4,"number_of_logical_processors":0,"number_of_logicalprocessors":8},

17:03:21.706 {"activity_name":"START","file":"C:\\Users\\owlyo\\Desktop\\Bot Text\\Text bot.neek
","script_id":"b8c90d98-e2a5-49c2-9ddd-28d77172bb59","memory_usage":117484,"version":{"launched_by":

Logs automáticos do Bot Runner

Para ativar o registro automático de logs:

  1. Clique com o botão direito no ícone do Bot Runner na bandeja do sistema.
  2. Acesse o menu “Configurações”.
  1. Acesse a aba “Execução”.
  2. Marque a caixa “Criar registros automaticamente para cada execução”.

Os logs automáticos podem ser encontrados na pasta C:\Users\{Username}\ElectroNeek\logs\robot ou simplesmente clicando no botão “Abrir registros” (clique com o botão direito no ícone do Bot Runner na bandeja do sistema).

Os logs automáticos contêm as seguintes informações:

  • Informações do ambiente:
    • Standalone ou dependente.
    • Versão do aplicativo.
    • Versão do Google Chrome/MS Edge.
    • Versão do Webdriver.
    • Versão da extensão.
    • Informações do usuário:
      • Região.
      • uID.
      • Licença.
      • Permissões.
  • Eventos:
    • Flags do processo.
    • Login - com um link para um arquivo .neek.
    • Logoff.
    • Início do fluxo de trabalho.
    • Fim do fluxo de trabalho.
    • Mensagens do console do Studio Pro.
  • Eventos de rede:
    • Solicitações com falha, com URL, parâmetros e mensagem.
    • Conexão a sockets (com URL).
    • Falhas de conexão a sockets (com URL).

Como excluir o Bot Runner das verificações do antivírus

Em alguns casos, devido a diversas configurações, os antivírus não confiam em aplicativos de terceiros e os bloqueiam. Se a plataforma ElectroNeek não iniciar, um dos possíveis motivos pode ser o bloqueio por um antivírus. Nesse caso, recomendamos entrar em contato com o administrador do sistema para adicionar determinados arquivos à lista de exceções do antivírus. Abaixo está a lista de arquivos do "Bot Runner".

  • C:\Program Files\ElectroNeek Robot\ElectroNeek Bot Runner.exe
  • C:\Program Files\ElectroNeek Robot\win-agent-selectors\ElectroNeek-Robot.exe
  • C:\Program Files\ElectroNeek Robot\Loader\ElectroNeek-loader.exe

Como instalar o Bot Runner silenciosamente e conectá-lo ao Orquestrador

Em alguns cenários, pode ser necessário instalar o Bot Runner em "modo silencioso", ou seja, sem usar a interface gráfica do instalador. Essa é uma solicitação comum em arquiteturas de grande escala, nas quais pode ser preciso instalar (ou atualizar) o Bot Runner em várias máquinas. Fazer isso manualmente pode consumir muito tempo valioso, por isso oferecemos um método para realizar a instalação com um comando simples, além de uma forma de conectar o Bot Runner recém-instalado a um Orquestrador de maneira programática. Por fim, apresentamos uma solução integrada para executar todas essas etapas em sequência.

Instalar o Bot Runner usando um comando

🚧Importante

Certifique-se de definir a política de execução do PowerShell adequadamente antes de executar scripts do PowerShell em uma máquina. Por exemplo, é possível usar o seguinte comando antes de executar qualquer script:

 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Para instalar o aplicativo Bot Runner em uma máquina usando um comando, primeiro baixe o instalador do Bot Runner e coloque-o em uma pasta de sua escolha.

Em seguida, abra um terminal do PowerShell como Administrador.

No terminal do PowerShell, execute o seguinte comando:

Start-Process -FilePath "[installer path]" -ArgumentList "/exenoui /quiet /norestart" -Wait -PassThru -Verb RunAs

Esse comando executa o instalador do Bot Runner "silenciosamente", sem nenhuma interface gráfica de usuário, e com permissões de Administrador (necessárias para a instalação).

Conectar o Bot Runner ao Orquestrador usando comandos

📘

Antes de seguir as etapas desta seção, certifique-se de conhecer as conexões por token no Orquestrador. Leia o seguinte artigo para obter mais informações: Conexão com o Orquestrador SaaS - Conexão por token

Após instalar o Bot Runner, pode ser desejável conectá-lo ao Orquestrador de forma programática usando um token, sem precisar abrir o aplicativo manualmente e colar o token. Isso pode ser feito com mais alguns comandos do PowerShell, que executarão as seguintes etapas:

  1. Criar o arquivo de licença do Bot Runner (AppData\Roaming\ElectroNeek\electroneek_license_key_3.0)
  2. Preencher o arquivo de licença com um token gerado previamente no Orquestrador
  3. Fechar e reiniciar o aplicativo Bot Runner para que o token seja registrado

Essas tarefas podem ser realizadas com os seguintes comandos:

# Delete the Bot Runner license file (if it exists -- if Bot Runner was installed for the first time, it will not exist, and you can skip this command)
Remove-Item "C:\Users\[username]\AppData\Roaming\ElectroNeek\electroneek_license_key_3.0" -Force

# Create the Bot Runner license file with the Token as its content
Set-Content -Path "C:\Users\[username]\AppData\Roaming\ElectroNeek\electroneek_license_key_3.0" -Value "[your full Token from Orchestrator]" -Force -NoNewLine

# Stop the ElectroNeek Bot Runner processes
Stop-Process -Name "ElectroNeek Bot Runner" -Force -ErrorAction Stop

# Start the ElectroNeek Bot Runner process again
Start-Process cmd.exe -ArgumentList "/c `"C:\Program Files\ElectroNeek Robot\ElectroNeek Bot Runner.exe`"" -WindowStyle Hidden

O último comando abre o Bot Runner por meio de uma instância do Prompt de Comando do Windows (cmd), para tornar o novo processo do Bot Runner independente do terminal do PowerShell. Se fosse usado um comando mais simples para a execução do aplicativo diretamente pelo PowerShell (como Start-Process -FilePath "C:\Program Files\ElectroNeek Robot\ElectroNeek Bot Runner.exe"), o aplicativo Bot Runner seria fechado ao fechar o terminal do PowerShell.

Depois de realizar essas etapas, ainda será necessário aprovar o Bot Runner na página "Bot Runners" do Orquestrador. Essa etapa não pode ser automatizada, pois é uma etapa de segurança obrigatória para permitir que um Bot Runner opere em um Orquestrador. No entanto, essa etapa não precisa ser feita na máquina do Bot Runner e pode ser realizada no ElectroNeek Portal com um navegador da Web em qualquer máquina.

Realizar a instalação silenciosa e a conexão por token do Bot Runner de uma só vez

🚧Importante

Certifique-se de definir a política de execução do PowerShell adequadamente antes de executar scripts do PowerShell em uma máquina. Por exemplo, é possível usar o seguinte comando antes de executar qualquer script:

 Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Preparamos o seguinte script do PowerShell, que pode ser usado para instalar e conectar o Bot Runner em qualquer máquina com 3 parâmetros simples:

  • InstallerPath = Caminho para o instalador do Bot Runner baixado previamente (no formato .EXE)
  • LicenseToken = O token de conexão completo gerado no Orquestrador
  • TargetUsername = (Opcional) O nome de usuário do Windows. Se não for informado, o script tentará identificá-lo automaticamente.
<#
.SYNOPSIS
    Installs ElectroNeek Bot Runner and configures license key
.DESCRIPTION
    This script installs ElectroNeek Bot Runner, replaces the license key file,
    and restarts the application. Suitable for deployment via RMM tools.
.PARAMETER InstallerPath
    Full path to the ElectroNeek Bot Runner installer EXE file
.PARAMETER LicenseToken
    The license token string to write to the license key file
.PARAMETER TargetUsername
    Optional: Specific username to target. If not provided, attempts to find the user automatically.
.EXAMPLE
    .\Install-ElectroNeek.ps1 -InstallerPath "C:\Temp\setup.exe" -LicenseToken "your-token-here"
.EXAMPLE
    .\Install-ElectroNeek.ps1 -InstallerPath "C:\Temp\setup.exe" -LicenseToken "abc123" -TargetUsername "jsmith"
#>

param(
    [Parameter(Mandatory=$true)]
    [string]$InstallerPath,
    
    [Parameter(Mandatory=$true)]
    [string]$LicenseToken,
    
    [Parameter(Mandatory=$false)]
    [string]$TargetUsername = ""
)

# Constants
$APP_PROCESS_NAME = "ElectroNeek Bot Runner"
$APP_EXE_PATH = "C:\Program Files\ElectroNeek Robot\ElectroNeek Bot Runner.exe"

# Function to write log messages
function Write-Log {
    param([string]$Message, [string]$Level = "INFO")
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    Write-Host "[$timestamp] [$Level] $Message"
}

# Function to install application
function Install-Application {
    param([string]$ExePath)
    
    Write-Log "Starting silent installation of: $ExePath"
    
    if (-not (Test-Path $ExePath)) {
        Write-Log "ERROR: Installer not found at path: $ExePath" -Level "ERROR"
        return $false
    }
    
    try {
        # Using /exenoui /quiet /norestart for completely silent installation
        # -Verb RunAs elevates to admin without prompting (requires script to run as admin)
        $process = Start-Process -FilePath $ExePath -ArgumentList "/exenoui /quiet /norestart" -Wait -PassThru -Verb RunAs
        
        Write-Log "Installation process completed with exit code: $($process.ExitCode)"
        
        # Wait additional time for installation to fully complete
        Start-Sleep -Seconds 5
        
        return $true
    }
    catch {
        Write-Log "ERROR during installation: $_" -Level "ERROR"
        return $false
    }
}

# Function to get target user directory
function Get-TargetUserPath {
    param([string]$Username)
    
    if ($Username -ne "") {
        $userPath = "C:\Users\$Username"
        if (Test-Path $userPath) {
            Write-Log "Using specified username: $Username"
            return $userPath
        } else {
            Write-Log "Specified user path not found: $userPath" -Level "WARNING"
        }
    }
    
    # Try to find the most recently modified user profile (excluding system accounts)
    $excludedUsers = @("Public", "Default", "Default User", "All Users")
    $userProfiles = Get-ChildItem "C:\Users" -Directory | 
        Where-Object { $excludedUsers -notcontains $_.Name } |
        Sort-Object LastWriteTime -Descending |
        Select-Object -First 1
    
    if ($userProfiles) {
        Write-Log "Auto-detected user: $($userProfiles.Name)"
        return $userProfiles.FullName
    }
    
    Write-Log "ERROR: Could not determine target user directory" -Level "ERROR"
    return $null
}

# Function to handle license key file
function Set-LicenseKey {
    param(
        [string]$UserPath,
        [string]$Token
    )
    
    $licenseFilePath = Join-Path $UserPath "AppData\Roaming\ElectroNeek\electroneek_license_key_3.0"
    $licenseDir = Split-Path $licenseFilePath -Parent
    
    Write-Log "Target license file path: $licenseFilePath"
    
    # Step 2: Check and delete existing file if it exists
    if (Test-Path $licenseFilePath) {
        try {
            Remove-Item $licenseFilePath -Force
            Write-Log "Deleted existing license file"
        }
        catch {
            Write-Log "ERROR deleting license file: $_" -Level "ERROR"
            return $false
        }
    } else {
        Write-Log "No existing license file found - skipping deletion step"
    }
    
    # Step 3: Ensure directory exists
    if (-not (Test-Path $licenseDir)) {
        try {
            New-Item -ItemType Directory -Path $licenseDir -Force | Out-Null
            Write-Log "Created directory: $licenseDir"
        }
        catch {
            Write-Log "ERROR creating directory: $_" -Level "ERROR"
            return $false
        }
    }
    
    # Step 3: Create new license file with token
    try {
        Set-Content -Path $licenseFilePath -Value $Token -Force -NoNewline
        Write-Log "Successfully created license file with token"
        
        # Verify the file was created
        if (Test-Path $licenseFilePath) {
            $content = Get-Content $licenseFilePath -Raw
            Write-Log "License file verified. Content length: $($content.Length) characters"
            return $true
        } else {
            Write-Log "ERROR: License file was not created" -Level "ERROR"
            return $false
        }
    }
    catch {
        Write-Log "ERROR creating license file: $_" -Level "ERROR"
        return $false
    }
}

# Function to stop all instances of ElectroNeek Bot Runner
function Stop-ElectroNeekProcess {
    Write-Log "Checking for running ElectroNeek Bot Runner processes..."
    
    try {
        $processes = Get-Process -Name "ElectroNeek Bot Runner" -ErrorAction SilentlyContinue
        
        if ($processes) {
            Write-Log "Found $($processes.Count) running instance(s). Stopping..."
            Stop-Process -Name "ElectroNeek Bot Runner" -Force -ErrorAction Stop
            
            # Wait a moment to ensure processes are fully terminated
            Start-Sleep -Seconds 2
            Write-Log "All ElectroNeek Bot Runner processes stopped"
        } else {
            Write-Log "No running ElectroNeek Bot Runner processes found"
        }
        
        return $true
    }
    catch {
        Write-Log "ERROR while stopping processes: $_" -Level "ERROR"
        return $false
    }
}

# Function to start ElectroNeek Bot Runner
function Start-ElectroNeekProcess {
    Write-Log "Starting ElectroNeek Bot Runner from: $APP_EXE_PATH"
    
    if (-not (Test-Path $APP_EXE_PATH)) {
        Write-Log "ERROR: ElectroNeek Bot Runner executable not found at: $APP_EXE_PATH" -Level "ERROR"
        return $false
    }
    
    try {
        # Create a temporary VBS script to launch the app hidden and independently
        $vbsScript = @"
Set objShell = CreateObject("WScript.Shell")
objShell.Run """$APP_EXE_PATH""", 0, False
"@
        $vbsPath = "$env:TEMP\StartElectroNeek.vbs"
        Set-Content -Path $vbsPath -Value $vbsScript -Force
        
        # Run the VBS script and then delete it
        Start-Process wscript.exe -ArgumentList "`"$vbsPath`"" -WindowStyle Hidden
        Start-Sleep -Seconds 1
        Remove-Item $vbsPath -Force -ErrorAction SilentlyContinue
        
        Write-Log "ElectroNeek Bot Runner started successfully"
        return $true
    }
    catch {
        Write-Log "ERROR starting ElectroNeek Bot Runner: $_" -Level "ERROR"
        return $false
    }
}

# Main execution
Write-Log "=========================================="
Write-Log "ElectroNeek Bot Runner Installation & Configuration"
Write-Log "=========================================="

# Step 1: Install the application
Write-Log "STEP 1: Installing ElectroNeek Bot Runner..."
$installSuccess = Install-Application -ExePath $InstallerPath

if (-not $installSuccess) {
    Write-Log "Installation failed. Exiting." -Level "ERROR"
    exit 1
}

# Get user path for license operations
$userPath = Get-TargetUserPath -Username $TargetUsername

if ($null -eq $userPath) {
    Write-Log "Could not determine user path. Exiting." -Level "ERROR"
    exit 1
}

# Steps 2 & 3: Handle license key file
Write-Log "STEPS 2 & 3: Managing license key file..."
$licenseSuccess = Set-LicenseKey -UserPath $userPath -Token $LicenseToken

if (-not $licenseSuccess) {
    Write-Log "License key configuration failed. Exiting." -Level "ERROR"
    exit 1
}

# Step 4: Stop all running instances
Write-Log "STEP 4a: Stopping ElectroNeek Bot Runner processes..."
$stopSuccess = Stop-ElectroNeekProcess

if (-not $stopSuccess) {
    Write-Log "Warning: Issues encountered while stopping processes, but continuing..." -Level "WARNING"
}

# Step 4: Start the application
Write-Log "STEP 4b: Starting ElectroNeek Bot Runner..."
$startSuccess = Start-ElectroNeekProcess

if (-not $startSuccess) {
    Write-Log "Failed to start ElectroNeek Bot Runner. Exiting." -Level "ERROR"
    exit 1
}

Write-Log "=========================================="
Write-Log "All steps completed successfully!"
Write-Log "=========================================="
exit 0

Salve esse script em um arquivo chamado Install-Electroneek.ps1 e execute-o com o seguinte comando, em um terminal do PowerShell aberto como Administrador:

.\Install-ElectroNeek.ps1 -InstallerPath "[full path to the Bot Runner installer]" -TargetUsername "[Windows user name, if left empty will auto-detect]" -LicenseToken "[the full Token from Orchestrator]"

Várias mensagens serão exibidas no terminal do PowerShell, indicando que o script está funcionando conforme o esperado ou relatando quaisquer erros que possam ocorrer.


Atualizado