Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@

## Features

- **🩺 Full Machine Health Check & Score (`health:check`):**
- Calculates an objective **0–100 Health Score** across RAM usage, disk storage, internet/DNS connectivity, print queue state, and critical OS logs, classifying the workstation into **Healthy (`80–100`)**, **Warning (`50–79`)**, or **Critical (`0–49`)** with visual progress bar, checklist (`✅` / `⚠️` / `❌`), and actionable remediation recommendations.
- **🖥 System & Hardware Diagnostics (`system`):**
- Inspect OS metadata, kernel version, architecture, hostname, and system uptime.
- Real-time CPU model, core/thread count, load percentage, and physical RAM usage.
- Storage volume capacity, used/free space, and usage percentages across NTFS/ext4/btrfs/xfs filesystems.
- Top resource-consuming processes viewer with interactive frozen process termination (`PID` kill).
- **Critical OS Logs & Recent Errors (`system:logs`):** Inspect critical and error events recorded in the last 24 hours (`Get-WinEvent` on Windows / `journalctl -p err` & `/var/log/syslog` on Linux).
- **🖨 Printers & Spooler Management (`printer`):**
- List installed printers, driver details, ports/URIs, default status, and queue states (`PowerShell Get-Printer` on Windows / `CUPS lpstat` on Linux).
- One-step print queue purge and spooler service restart (`net stop/start spooler` & `PRINTERS` cleanup on Windows / `cancel -a` & `systemctl restart cups` on Linux).
Expand All @@ -33,9 +36,11 @@
- **🧹 System Maintenance & Cleanup (`maintenance`):**
- Safe cleanup of user and system temporary directories (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`, `~/.cache/thumbnails`), gracefully skipping locked/in-use files and reporting freed disk space.
- **📄 Diagnostic Reports & Export (`report`):**
- Export complete hardware, OS, printer, and network diagnostic snapshots to structured `.txt` or `.json` files for ticketing systems and audit logs.
- Export complete hardware, OS, printer, and network diagnostic snapshots to structured `.md` and `.json` files for ticketing systems and audit logs.
- **⬆️ Over-the-Air Self-Update (`self:update`):**
- Automatically queries GitHub Releases for newer versions and atomically updates the running standalone binary (`.exe`, Linux ELF, or `.phar`) in-place.
- **🌍 Native Bilingual Interface (`i18n`):**
- Full support for **English (`en`)** and **Brazilian Portuguese (`pt_BR`)**, selectable via `--lang=` flag or dynamically inside the interactive TUI menu.
- Full support for **English (`en`)** and **Brazilian Portuguese (`pt_BR`)**, selectable via `--lang=` flag or dynamically inside the interactive numeric TUI menu.

---

Expand Down Expand Up @@ -139,16 +144,19 @@ Every module can also be executed directly in headless/CLI scripts or terminal s

| Command | Module | Description | Options |
| :--- | :--- | :--- | :--- |
| `php it-toolbox menu` | Core TUI | Launch the interactive TUI main menu (default command) | `--lang=en\|pt_BR`, `--once` |
| `php it-toolbox menu` | Core TUI | Launch the interactive numeric TUI main menu (default command) | `--lang=en\|pt_BR`, `--once` |
| `php it-toolbox health:check` | Health | Run a full machine health audit with a 0–100 score and recommendations | `--export`, `--lang=en\|pt_BR` |
| `php it-toolbox system:info` | System | Display OS, CPU, RAM, and disk health metrics | `--lang=en\|pt_BR` |
| `php it-toolbox system:top` | System | List top processes by resource usage and optionally kill a PID | `--limit=10`, `--lang=en\|pt_BR` |
| `php it-toolbox system:logs` | System | Inspect critical and error OS log events from the last 24 hours | `--limit=15`, `--lang=en\|pt_BR` |
| `php it-toolbox printer:list` | Printers | List installed printers, drivers, ports, and status | `--lang=en\|pt_BR` |
| `php it-toolbox printer:clear` | Printers | Restart print spooler / CUPS and purge stuck print jobs | `--force`, `--lang=en\|pt_BR` |
| `php it-toolbox network:check` | Network | Inspect network interfaces and run ping/DNS health checks | `--lang=en\|pt_BR` |
| `php it-toolbox network:flush` | Network | Flush DNS resolver cache and renew DHCP lease | `--force`, `--lang=en\|pt_BR` |
| `php it-toolbox network:ports` | Network | List active listening TCP/UDP ports and owning processes | `--lang=en\|pt_BR` |
| `php it-toolbox clean:temp` | Maintenance | Safely purge temporary files and report freed space | `--force`, `--lang=en\|pt_BR` |
| `php it-toolbox report:export` | Reports | Export full system diagnostic report to `.md` and/or `.json` | `--format=md\|json\|both`, `--output=DIR`, `--lang=en\|pt_BR` |
| `php it-toolbox self:update` | Core CLI | Check GitHub Releases and self-update the running executable | `--check`, `--lang=en\|pt_BR` |

---

Expand Down
14 changes: 11 additions & 3 deletions README.pt-BR.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@ O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TU

## Funcionalidades

- **🩺 Check-up Geral & Score de Saúde da Máquina (`health:check`):**
- Calcula um **Score de Saúde objetivo de 0 a 100 pontos** auditando consumo de RAM, armazenamento em disco, conectividade externa/DNS, fila de impressão e logs críticos do SO, classificando a máquina em **Saudável (`80–100`)**, **Atenção (`50–79`)** ou **Crítico (`0–49`)** com barra visual de integridade, checklist (`✅` / `⚠️` / `❌`) e recomendações práticas de correção.
- **🖥 Diagnóstico de Sistema e Hardware (`system`):**
- Inspeção de metadados do SO, versão do kernel, arquitetura, hostname e tempo de atividade (`uptime`).
- Modelo da CPU, contagem de núcleos/threads, percentual de carga em tempo real e uso de memória RAM física.
- Capacidade de volumes de armazenamento, espaço usado/livre e percentual de ocupação em sistemas de arquivos NTFS/ext4/btrfs/xfs.
- Visualizador dos processos de maior consumo com opção interativa para encerrar tarefas travadas (`kill PID`).
- **Logs Críticos do SO & Erros Recentes (`system:logs`):** Inspeção de eventos críticos e erros registrados nas últimas 24 horas (`Get-WinEvent` no Windows / `journalctl -p err` e `/var/log/syslog` no Linux).
- **🖨 Gerenciamento de Impressoras e Spooler (`printer`):**
- Listagem de impressoras instaladas, detalhes de drivers, portas/URIs, impressora padrão e status da fila (`PowerShell Get-Printer` no Windows / `CUPS lpstat` no Linux).
- Limpeza automatizada de fila de impressão e reinicialização do serviço de spooler (`net stop/start spooler` e limpeza de `PRINTERS` no Windows / `cancel -a` e `systemctl restart cups` no Linux).
Expand All @@ -33,9 +36,11 @@ O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TU
- **🧹 Manutenção e Limpeza do Sistema (`maintenance`):**
- Limpeza segura de diretórios temporários de usuário e sistema (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`, `~/.cache/thumbnails`), ignorando arquivos em uso/bloqueados com segurança e contabilizando o espaço em disco liberado.
- **📄 Relatórios de Diagnóstico e Exportação (`report`):**
- Exportação de relatórios completos de diagnóstico de hardware, SO, impressoras e rede nos formatos `.txt` ou `.json` para anexação em chamados técnicos e auditorias.
- Exportação de relatórios completos de diagnóstico de hardware, SO, impressoras e rede nos formatos `.md` e `.json` para anexação em chamados técnicos e auditorias.
- **⬆️ Auto-Atualização via GitHub Releases (`self:update`):**
- Consulta automaticamente a API do GitHub Releases em busca de novas versões e atualiza o binário em execução (`.exe`, binário Linux ou `.phar`) de forma atômica.
- **🌍 Interface Bilíngue Nativa (`i18n`):**
- Suporte completo para **Inglês (`en`)** e **Português do Brasil (`pt_BR`)**, selecionável via flag `--lang=` ou dinamicamente dentro do menu interativo TUI.
- Suporte completo para **Inglês (`en`)** e **Português do Brasil (`pt_BR`)**, selecionável via flag `--lang=` ou dinamicamente dentro do menu interativo numérico TUI.

---

Expand Down Expand Up @@ -139,16 +144,19 @@ Cada módulo também pode ser executado diretamente em scripts ou sessões rápi

| Comando | Módulo | Descrição | Opções |
| :--- | :--- | :--- | :--- |
| `php it-toolbox menu` | Core TUI | Inicia o menu principal interativo TUI (comando padrão) | `--lang=en\|pt_BR`, `--once` |
| `php it-toolbox menu` | Core TUI | Inicia o menu principal interativo numérico TUI (comando padrão) | `--lang=en\|pt_BR`, `--once` |
| `php it-toolbox health:check` | Saúde | Executa auditoria completa com Score de Saúde (0–100) e recomendações | `--export`, `--lang=en\|pt_BR` |
| `php it-toolbox system:info` | Sistema | Exibe métricas de SO, CPU, RAM e saúde de discos | `--lang=en\|pt_BR` |
| `php it-toolbox system:top` | Sistema | Lista os processos de maior consumo e permite encerrar um PID | `--limit=10`, `--lang=en\|pt_BR` |
| `php it-toolbox system:logs` | Sistema | Exibe eventos críticos e erros de log do SO nas últimas 24 horas | `--limit=15`, `--lang=en\|pt_BR` |
| `php it-toolbox printer:list` | Impressoras | Lista impressoras instaladas, drivers, portas e status | `--lang=en\|pt_BR` |
| `php it-toolbox printer:clear` | Impressoras | Reinicia o Spooler / CUPS e limpa trabalhos de impressão travados | `--force`, `--lang=en\|pt_BR` |
| `php it-toolbox network:check` | Rede | Inspeciona interfaces de rede e executa testes de ping e DNS | `--lang=en\|pt_BR` |
| `php it-toolbox network:flush` | Rede | Limpa o cache DNS e renova a concessão de IP via DHCP | `--force`, `--lang=en\|pt_BR` |
| `php it-toolbox network:ports` | Rede | Lista portas TCP/UDP em escuta e seus respectivos processos | `--lang=en\|pt_BR` |
| `php it-toolbox clean:temp` | Manutenção | Limpa diretórios temporários com segurança e exibe espaço liberado | `--force`, `--lang=en\|pt_BR` |
| `php it-toolbox report:export` | Relatórios | Exporta relatório completo de diagnóstico em `.md` e/ou `.json` | `--format=md\|json\|both`, `--output=DIR`, `--lang=en\|pt_BR` |
| `php it-toolbox self:update` | Core CLI | Verifica novas versões no GitHub Releases e auto-atualiza o binário | `--check`, `--lang=en\|pt_BR` |

---

Expand Down
132 changes: 132 additions & 0 deletions app/Commands/System/HealthCheckCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

declare(strict_types=1);

namespace App\Commands\System;

use App\Commands\Concerns\InteractsWithLocale;
use App\Services\HealthCheckService;
use App\Services\ReportExporterService;
use LaravelZero\Framework\Commands\Command;

use function Laravel\Prompts\confirm;
use function Laravel\Prompts\error;
use function Laravel\Prompts\info;
use function Laravel\Prompts\note;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\table;
use function Laravel\Prompts\warning;

class HealthCheckCommand extends Command
{
use InteractsWithLocale;

/**
* The signature of the command.
*
* @var string
*/
protected $signature = 'health:check
{--export : Automatically export the full diagnostic report in MD and JSON}
{--lang= : Interface language (en or pt_BR)}';

/**
* The description of the command.
*
* @var string
*/
protected $description = 'Run a comprehensive system health check with a 0-100 health score and action recommendations';

/**
* Execute the console command.
*/
public function handle(HealthCheckService $healthService, ReportExporterService $exporter): int
{
$locale = $this->resolveLocale();

$audit = spin(
callback: fn (): array => $healthService->runAudit(),
message: (string) __('messages.spinners.health_check'),
);

info((string) __('messages.health.section'));

$scoreBanner = sprintf(
'%s: %s (%s)',
(string) __('messages.health.score_label'),
$audit['progress_bar'],
$audit['state_label']
);

match ($audit['state']) {
'healthy' => info($scoreBanner),
'warning' => warning($scoreBanner),
default => error($scoreBanner),
};

table(
headers: [
(string) __('messages.health.headers.category'),
(string) __('messages.health.headers.status'),
(string) __('messages.health.headers.summary'),
(string) __('messages.health.headers.impact'),
],
rows: array_map(
fn (array $item): array => [
$item['category'],
sprintf('%s %s', $item['icon'], $item['status']),
$item['summary'],
$item['penalty'] > 0 ? sprintf('-%d pts', $item['penalty']) : '0 pts',
],
$audit['checks']
),
);

if ($audit['recommendations'] !== []) {
warning((string) __('messages.health.recommendations_title'));
$recLines = array_map(
fn (string $rec): string => sprintf(' • %s', $rec),
$audit['recommendations']
);
note(implode(PHP_EOL, $recLines));
} else {
info((string) __('messages.health.no_recommendations'));
}

$shouldExport = (bool) $this->option('export');

if (! $shouldExport && $this->input->isInteractive()) {
$shouldExport = confirm(
label: (string) __('messages.health.ask_export'),
default: false,
yes: (string) __('messages.common.yes'),
no: (string) __('messages.common.no'),
);
}

if ($shouldExport) {
$exportResult = spin(
callback: fn () => $exporter->export(
format: 'both',
outputDirectory: null,
locale: $locale,
timestamp: null,
healthAudit: $audit,
),
message: (string) __('messages.spinners.report_export'),
);

$paths = isset($exportResult->details['paths']) && is_array($exportResult->details['paths'])
? implode(', ', array_map('strval', $exportResult->details['paths']))
: '';

if ($exportResult->success) {
info((string) __('messages.report.exported_success', ['path' => $paths]));
} else {
error((string) __('messages.report.exported_failed', ['path' => $paths]));
}
}

return self::SUCCESS;
}
}
82 changes: 82 additions & 0 deletions app/Commands/System/LogsCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

declare(strict_types=1);

namespace App\Commands\System;

use App\Commands\Concerns\InteractsWithLocale;
use App\Contracts\SystemDriverInterface;
use LaravelZero\Framework\Commands\Command;

use function Laravel\Prompts\info;
use function Laravel\Prompts\spin;
use function Laravel\Prompts\table;

class LogsCommand extends Command
{
use InteractsWithLocale;

/**
* The signature of the command.
*
* @var string
*/
protected $signature = 'system:logs
{--limit=15 : Maximum number of critical/error log events to retrieve}
{--lang= : Interface language (en or pt_BR)}';

/**
* The description of the command.
*
* @var string
*/
protected $description = 'Inspect recent critical and error events from the OS event log / journal (last 24h)';

/**
* Execute the console command.
*/
public function handle(SystemDriverInterface $driver): int
{
$this->resolveLocale();

$limit = max(1, (int) $this->option('limit'));

$result = spin(
callback: fn () => $driver->getCriticalLogs($limit),
message: (string) __('messages.spinners.system_logs'),
);

info((string) __('messages.logs.section'));

/** @var array<int, array{timestamp?: string, level?: string, source?: string, message?: string}> $events */
$events = isset($result->details['events']) && is_array($result->details['events'])
? $result->details['events']
: [];

if ($events === []) {
info((string) __('messages.logs.no_logs'));

return self::SUCCESS;
}

table(
headers: [
(string) __('messages.logs.headers.timestamp'),
(string) __('messages.logs.headers.level'),
(string) __('messages.logs.headers.source'),
(string) __('messages.logs.headers.message'),
],
rows: array_map(
fn (array $event): array => [
(string) ($event['timestamp'] ?? '-'),
(string) ($event['level'] ?? 'ERROR'),
(string) ($event['source'] ?? '-'),
(string) ($event['message'] ?? '-'),
],
$events
),
);

return self::SUCCESS;
}
}
Loading
Loading