# /server-health - Comandos SSH e Template de Output

## Comandos por Passo

### Passo 1: Sistema

```bash
uptime
free -h
df -h
top -bn1 | head -20
cat /proc/loadavg
vmstat 1 3
ps aux | grep -E 'httpd|mysql|nginx' | grep -v grep
```

**Validação:**
- Load 1min <2: OK | 2-5: Warning | >5: Critical
- RAM <70%: OK | Swap >10%: Investigar

### Passo 2: MySQL

```bash
mysqladmin status
mysqladmin processlist | head -20
mysql -e "SHOW GLOBAL STATUS LIKE 'Threads%';"
mysql -e "SHOW GLOBAL STATUS LIKE 'Slow_queries';"
mysql -e "SELECT table_schema, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS 'Size (MB)' FROM information_schema.TABLES GROUP BY table_schema ORDER BY SUM(data_length + index_length) DESC LIMIT 10;"
mysqlcheck --all-databases --check
```

**Queries Críticas:**
```sql
-- Ver queries lentas em execução
SELECT id, user, host, db, command, time, state, LEFT(info, 100) as query
FROM information_schema.PROCESSLIST
WHERE command != 'Sleep' AND time > 5
ORDER BY time DESC;

-- BDs maiores que 500MB
SELECT table_schema, ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
FROM information_schema.TABLES
GROUP BY table_schema
HAVING size_mb > 500
ORDER BY size_mb DESC;
```

### Passo 3: Web Servers

```bash
systemctl status httpd --no-pager | head -15
systemctl status nginx --no-pager | head -15
curl -sI localhost | head -10
curl -sI -H 'Accept-Encoding: gzip' localhost | grep -i encoding
netstat -an | grep :80 | wc -l
netstat -an | grep :443 | wc -l
httpd -S 2>&1 | grep -E 'port|namevhost' | head -20
```

### Passo 4: PHP

```bash
php -v | head -1
php -i | grep memory_limit
php -i | grep -E 'opcache.enable|opcache.memory_consumption'
ps aux | grep php-fpm | wc -l
```

### Passo 5: SSL/Certificados

```bash
ls -lh /root/.acme.sh/cwp_certs/

for d in $(ls /root/.acme.sh/cwp_certs/); do
  echo "=== $d ==="
  grep -E 'Le_NextRenewTimeStr|Le_Alt' /root/.acme.sh/cwp_certs/$d/*.conf 2>/dev/null | head -3
done

echo | openssl s_client -connect DOMINIO:443 2>/dev/null | openssl x509 -noout -dates -subject
tail -100 /root/.acme.sh/acme.sh.log | grep -E 'Renew|error|success'
```

**Validação SSL:**
- Renovação >30 dias: OK | 15-30 dias: Avisar | <15 dias: Urgente

### Passo 6: Segurança

```bash
systemctl status fail2ban --no-pager 2>/dev/null
fail2ban-client status 2>/dev/null | head -10
fail2ban-client status sshd 2>/dev/null | grep "Banned IP"
netstat -tlnp | grep LISTEN | head -20
last -10
grep "Failed password" /var/log/secure | tail -20
systemctl status firewalld --no-pager || iptables -L -n | head -20
```

### Passo 7: Sites WordPress

```bash
for dir in /home/*/public_html; do
  if [ -f "$dir/wp-config.php" ]; then
    domain=$(basename $(dirname $dir))
    echo "=== $domain ==="
    grep "wp_version = " $dir/wp-includes/version.php | head -1
    du -sh $dir/wp-content
    curl -sI "http://$domain" | head -3
  fi
done
```

---

## Verificação Rápida (Quick Mode)

```bash
echo "=== QUICK HEALTH ===" && \
uptime && \
free -h | grep Mem && \
df -h | grep -E '^/dev/vda|Filesystem' && \
mysqladmin status 2>&1 | head -1 && \
systemctl is-active httpd nginx mysql
```

---

## MySQL Deep Dive

```bash
# Optimizar todas as BDs
mysqlcheck --optimize --all-databases

# Limpar logs binários antigos (>7 dias)
mysql -e "PURGE BINARY LOGS BEFORE DATE_SUB(NOW(), INTERVAL 7 DAY);"

# Verificar fragmentação
mysql -e "SELECT table_schema, table_name,
           ROUND(data_length/1024/1024,2) as data_mb,
           ROUND(data_free/1024/1024,2) as free_mb
           FROM information_schema.TABLES
           WHERE data_free > 0
           ORDER BY data_free DESC LIMIT 10;"
```

---

## Limpeza de Cache/Temp

```bash
# Limpar cache WordPress
find /home/*/public_html/wp-content/cache -type f -delete

# Limpar sessions PHP antigas
find /var/lib/php/session -type f -mtime +7 -delete

# Limpar logs Apache/Nginx >30 dias
find /home/*/logs -name "*.log" -mtime +30 -delete
```

---

## Template de Output

```markdown
# Server Health Report - YYYY-MM-DD HH:MM

## Resumo Executivo

| Métrica | Valor | Status | Limite |
|---------|-------|--------|--------|
| Load (1m) | X.XX | OK/Warn/Crit | <2 |
| RAM Usada | XX% | OK/Warn/Crit | <70% |
| Swap Usado | XX% | OK/Warn/Crit | <10% |
| Disco / | XX% | OK/Warn/Crit | <70% |
| MySQL Threads | XX | OK/Warn/Crit | <50 |
| Sites WP OK | XX/YY | OK/Warn/Crit | 100% |
| SSL Expiring | XX | OK/Warn/Crit | 0 |

**Health Score:** XX/100

---

## Alertas Críticos

> CRÍTICO: Load >5 há 10 minutos
> ATENÇÃO: Certificado SSL solarfv360.pt expira em 12 dias

---

## Recomendações Prioritárias

### URGENTE (Hoje)
1. Reduzir uso de Swap (45%)
2. Renovar SSL solarfv360.pt

### IMPORTANTE (Esta Semana)
3. Optimizar queries lentas MySQL

### MELHORIAS (Mês)
4. Configurar alertas automáticos
```

---

## Troubleshooting

### Swap Alto (>30%)
```bash
ps aux --sort=-%mem | head -10
swapoff -a && swapon -a
```

### Load Alto (>5)
```bash
ps aux --sort=-%cpu | head -10
iostat -x 1 5
top -bn1 | head -20
```

### MySQL Lento
```bash
mysqladmin processlist
tail -50 /var/log/mysql/slow.log
mysqlcheck --optimize --all-databases
```

### Sites WordPress com Erro
```bash
tail -100 /home/USER/logs/error.log
ls -lh /home/USER/public_html/wp-content
chown -R USER:USER /home/USER/public_html/wp-content
```
