ids.alfacom.it/extracted_idf/db_cleanup_cron_fixed.sh
marco370 0bfe3258b5 Saved progress at the end of the loop
Replit-Commit-Author: Agent
Replit-Commit-Session-Id: 7a657272-55ba-4a79-9a2e-f1ed9bc7a528
Replit-Commit-Checkpoint-Type: full_checkpoint
Replit-Commit-Event-Id: 1c71ce6e-1a3e-4f53-bb5d-77cdd22b8ea3
2025-11-11 09:15:10 +00:00

378 lines
13 KiB
Bash
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
# ============================================
# SCRIPT PULIZIA IP - ESECUZIONE VIA CRON (FIXED)
# Per database server MySQL/MariaDB
# Supporta pulizie orarie: 1h, 12h, 24h
# Versione corretta senza parametri DEFAULT
# ============================================
# Configurazione database
DB_HOST="localhost"
DB_USER="root"
DB_PASSWORD="Hdgtejskjjc0-"
DB_NAME="LOG_MIKROTIK"
LOG_FILE="/var/log/ddos_cleanup.log"
# Colori per output (se eseguito manualmente)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
MAGENTA='\033[0;35m'
NC='\033[0m'
# Funzione di logging
log_message() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
if [ -t 1 ]; then # Se eseguito da terminale
echo -e "${BLUE}$(date '+%H:%M:%S')${NC} - $1"
fi
}
log_success() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - SUCCESS: $1" >> "$LOG_FILE"
if [ -t 1 ]; then
echo -e "${GREEN}$1${NC}"
fi
}
log_error() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: $1" >> "$LOG_FILE"
if [ -t 1 ]; then
echo -e "${RED}$1${NC}"
fi
}
log_warning() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - WARNING: $1" >> "$LOG_FILE"
if [ -t 1 ]; then
echo -e "${YELLOW}⚠️ $1${NC}"
fi
}
log_info() {
echo "$(date '+%Y-%m-%d %H:%M:%S') - INFO: $1" >> "$LOG_FILE"
if [ -t 1 ]; then
echo -e "${CYAN} $1${NC}"
fi
}
# Funzione per eseguire query SQL
execute_sql() {
local query="$1"
local description="$2"
log_message "Esecuzione: $description"
result=$(mysql -h"$DB_HOST" -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" -e "$query" 2>&1)
exit_code=$?
if [ $exit_code -eq 0 ]; then
log_success "$description completata"
if [ -n "$result" ] && [ "$result" != "" ]; then
echo "$result" >> "$LOG_FILE"
# Mostra risultato anche a terminale se presente
if [ -t 1 ]; then
echo "$result"
fi
fi
return 0
else
log_error "$description fallita: $result"
return 1
fi
}
# Funzione principale di pulizia (giorni) - FIXED
cleanup_ips() {
local retention_days="${1:-7}"
local list_name="${2:-ddos_detect_v03}"
local dry_run_param="${3:-FALSE}"
log_message "=== INIZIO PULIZIA IP AUTOMATICA (GIORNI) ==="
log_message "Lista: $list_name, Ritenzione: $retention_days giorni, Dry run: $dry_run_param"
# Usa la stored procedure con parametri espliciti (no DEFAULT)
local sql="CALL cleanup_ddos_ips($retention_days, '$list_name', $dry_run_param);"
if execute_sql "$sql" "Pulizia IP lista $list_name"; then
log_success "Pulizia completata per lista $list_name"
return 0
else
log_error "Pulizia fallita per lista $list_name"
return 1
fi
}
# Funzione di pulizia oraria (FIXED)
cleanup_ips_hours() {
local retention_hours="${1:-24}"
local list_name="${2:-ddos_detect_v03}"
local dry_run_param="${3:-FALSE}"
log_message "=== INIZIO PULIZIA IP ORARIA ==="
log_message "Lista: $list_name, Ritenzione: $retention_hours ore, Dry run: $dry_run_param"
# Usa la stored procedure oraria con parametri espliciti
local sql="CALL cleanup_ddos_ips_hours($retention_hours, '$list_name', $dry_run_param);"
if execute_sql "$sql" "Pulizia ORARIA IP lista $list_name"; then
log_success "Pulizia oraria completata per lista $list_name ($retention_hours ore)"
return 0
else
log_error "Pulizia oraria fallita per lista $list_name"
return 1
fi
}
# Funzione per ottenere statistiche (aggiornata)
get_statistics() {
log_message "Raccolta statistiche IP con dettagli orari..."
# Query per statistiche generali con info orarie
local stats_query="
SELECT
list_name,
COUNT(*) as total_ips,
COUNT(CASE WHEN retrieved_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as last_1h,
COUNT(CASE WHEN retrieved_at >= DATE_SUB(NOW(), INTERVAL 12 HOUR) THEN 1 END) as last_12h,
COUNT(CASE WHEN retrieved_at >= DATE_SUB(NOW(), INTERVAL 1 DAY) THEN 1 END) as last_24h,
COUNT(CASE WHEN retrieved_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as last_7d,
COUNT(CASE WHEN retrieved_at < DATE_SUB(NOW(), INTERVAL 1 HOUR) THEN 1 END) as older_1h,
COUNT(CASE WHEN retrieved_at < DATE_SUB(NOW(), INTERVAL 12 HOUR) THEN 1 END) as older_12h,
COUNT(CASE WHEN retrieved_at < DATE_SUB(NOW(), INTERVAL 1 DAY) THEN 1 END) as older_24h,
COUNT(CASE WHEN retrieved_at < DATE_SUB(NOW(), INTERVAL 7 DAY) THEN 1 END) as older_7d
FROM ip_list
GROUP BY list_name;
"
execute_sql "$stats_query" "Raccolta statistiche complete"
# Mostra anche statistiche funzione personalizzata
echo ""
log_info "Statistiche dettagliate per ddos_detect_v03:"
execute_sql "SELECT get_ip_stats('ddos_detect_v03') as stats;" "Statistiche funzione personalizzata"
}
# Funzione per verificare connessione database
test_connection() {
log_message "Test connessione database..."
if execute_sql "SELECT 1 as test_connection" "Test connessione"; then
log_success "Connessione database OK"
# Test anche tabelle necessarie
execute_sql "SELECT COUNT(*) as ip_list_count FROM ip_list;" "Verifica tabella ip_list"
execute_sql "SELECT COUNT(*) as log_count FROM ip_cleanup_log;" "Verifica tabella ip_cleanup_log"
return 0
else
log_error "Connessione database fallita"
return 1
fi
}
# Funzione per pulizia completa (tutte le liste)
cleanup_all_lists() {
log_message "=== PULIZIA COMPLETA TUTTE LE LISTE ==="
# Lista principale DDoS Detection
cleanup_ips 7 "ddos_detect_v03" "FALSE"
# Altre liste esistenti (se presenti)
cleanup_ips 10 "ddos_ia" "FALSE"
cleanup_ips 15 "ddos2-attackers" "FALSE"
cleanup_ips 20 "ddos3-attackers" "FALSE"
# Pulizia log vecchi
local cleanup_log_query="DELETE FROM ip_cleanup_log WHERE operation_time < DATE_SUB(NOW(), INTERVAL 30 DAY);"
execute_sql "$cleanup_log_query" "Pulizia log vecchi"
log_message "=== PULIZIA COMPLETA TERMINATA ==="
}
# Funzioni di pulizia rapida predefinite (FIXED)
quick_cleanup_1h() {
local list_name="${1:-ddos_detect_v03}"
local dry_run_param="${2:-FALSE}"
echo -e "${MAGENTA}⚡ PULIZIA RAPIDA 1 ORA${NC}"
log_info "Pulizia rapida 1 ora per lista: $list_name"
if test_connection; then
cleanup_ips_hours 1 "$list_name" "$dry_run_param"
fi
}
quick_cleanup_12h() {
local list_name="${1:-ddos_detect_v03}"
local dry_run_param="${2:-FALSE}"
echo -e "${MAGENTA}⚡ PULIZIA RAPIDA 12 ORE${NC}"
log_info "Pulizia rapida 12 ore per lista: $list_name"
if test_connection; then
cleanup_ips_hours 12 "$list_name" "$dry_run_param"
fi
}
quick_cleanup_24h() {
local list_name="${1:-ddos_detect_v03}"
local dry_run_param="${2:-FALSE}"
echo -e "${MAGENTA}⚡ PULIZIA RAPIDA 24 ORE${NC}"
log_info "Pulizia rapida 24 ore per lista: $list_name"
if test_connection; then
cleanup_ips_hours 24 "$list_name" "$dry_run_param"
fi
}
# Funzione per usare procedure wrapper con default
use_default_procedures() {
log_info "Test procedure wrapper con valori default..."
echo ""
log_info "1. Test dry run con valori default (7 giorni):"
execute_sql "CALL cleanup_ddos_ips_dry_default();" "Dry run default"
echo ""
log_info "2. Test dry run orario con valori default (24 ore):"
execute_sql "CALL cleanup_ddos_ips_hours_dry_default();" "Dry run orario default"
}
# Parsing argomenti aggiornato
case "${1:-auto}" in
"test")
echo -e "${BLUE}🔧 TEST CONNESSIONE DATABASE${NC}"
test_connection
;;
"stats")
echo -e "${BLUE}📊 STATISTICHE IP LISTE (CON DETTAGLI ORARI)${NC}"
test_connection && get_statistics
;;
"dry-run")
echo -e "${BLUE}🔍 SIMULAZIONE PULIZIA${NC}"
retention_days="${2:-7}"
list_name="${3:-ddos_detect_v03}"
test_connection && cleanup_ips "$retention_days" "$list_name" "TRUE"
;;
"cleanup")
echo -e "${BLUE}🧹 PULIZIA MANUALE${NC}"
retention_days="${2:-7}"
list_name="${3:-ddos_detect_v03}"
test_connection && cleanup_ips "$retention_days" "$list_name" "FALSE"
;;
"dry-run-hours")
echo -e "${CYAN}🔍 SIMULAZIONE PULIZIA ORARIA${NC}"
retention_hours="${2:-24}"
list_name="${3:-ddos_detect_v03}"
test_connection && cleanup_ips_hours "$retention_hours" "$list_name" "TRUE"
;;
"cleanup-hours")
echo -e "${CYAN}🧹 PULIZIA ORARIA MANUALE${NC}"
retention_hours="${2:-24}"
list_name="${3:-ddos_detect_v03}"
test_connection && cleanup_ips_hours "$retention_hours" "$list_name" "FALSE"
;;
"1h"|"1hour")
quick_cleanup_1h "${2:-ddos_detect_v03}" "FALSE"
;;
"12h"|"12hours")
quick_cleanup_12h "${2:-ddos_detect_v03}" "FALSE"
;;
"24h"|"24hours")
quick_cleanup_24h "${2:-ddos_detect_v03}" "FALSE"
;;
"1h-dry"|"1hour-dry")
quick_cleanup_1h "${2:-ddos_detect_v03}" "TRUE"
;;
"12h-dry"|"12hours-dry")
quick_cleanup_12h "${2:-ddos_detect_v03}" "TRUE"
;;
"24h-dry"|"24hours-dry")
quick_cleanup_24h "${2:-ddos_detect_v03}" "TRUE"
;;
"test-defaults")
echo -e "${MAGENTA}🧪 TEST PROCEDURE CON VALORI DEFAULT${NC}"
test_connection && use_default_procedures
;;
"auto"|"")
# Modalità automatica (per cron)
if test_connection; then
cleanup_all_lists
get_statistics
fi
;;
"help"|"-h"|"--help")
echo -e "${GREEN}📖 USO SCRIPT PULIZIA IP DATABASE (VERSIONE FIXED)${NC}"
echo ""
echo "Uso: $0 [comando] [parametri]"
echo ""
echo -e "${YELLOW}Comandi principali:${NC}"
echo " auto - Pulizia automatica tutte le liste (default per cron)"
echo " test - Test connessione database e tabelle"
echo " stats - Mostra statistiche IP attuali (con dettagli orari)"
echo " test-defaults - Test procedure wrapper con valori default"
echo ""
echo -e "${YELLOW}Pulizie basate su giorni:${NC}"
echo " dry-run [gg] [lista] - Simulazione pulizia (default: 7 giorni, ddos_detect_v03)"
echo " cleanup [gg] [lista] - Pulizia manuale (default: 7 giorni, ddos_detect_v03)"
echo ""
echo -e "${CYAN}Pulizie basate su ore (NUOVO!):${NC}"
echo " dry-run-hours [h] [lista] - Simulazione pulizia oraria (default: 24 ore)"
echo " cleanup-hours [h] [lista] - Pulizia oraria manuale (default: 24 ore)"
echo ""
echo -e "${MAGENTA}Pulizie rapide predefinite:${NC}"
echo " 1h [lista] - Pulisci IP più vecchi di 1 ora"
echo " 12h [lista] - Pulisci IP più vecchi di 12 ore"
echo " 24h [lista] - Pulisci IP più vecchi di 24 ore"
echo " 1h-dry [lista] - Simula pulizia 1 ora"
echo " 12h-dry [lista] - Simula pulizia 12 ore"
echo " 24h-dry [lista] - Simula pulizia 24 ore"
echo ""
echo -e "${YELLOW}Esempi pulizie standard:${NC}"
echo " $0 test # Test connessione e tabelle"
echo " $0 stats # Statistiche complete"
echo " $0 dry-run 7 ddos_detect_v03 # Simula pulizia 7 giorni"
echo " $0 cleanup 3 ddos_detect_v03 # Pulisci IP più vecchi di 3 giorni"
echo ""
echo -e "${CYAN}Esempi pulizie orarie:${NC}"
echo " $0 1h # Pulisci IP > 1 ora (lista default)"
echo " $0 12h ddos_detect_v03 # Pulisci IP > 12 ore"
echo " $0 24h-dry # Simula pulizia IP > 24 ore"
echo " $0 cleanup-hours 6 ddos_ia # Pulisci IP > 6 ore lista ddos_ia"
echo " $0 dry-run-hours 2 ddos_detect_v03 # Simula pulizia IP > 2 ore"
echo ""
echo -e "${MAGENTA}Test nuove funzionalità:${NC}"
echo " $0 test-defaults # Test procedure wrapper con default"
echo ""
echo -e "${YELLOW}Configurazione cron per pulizia automatica:${NC}"
echo " # Pulizia quotidiana alle 02:30"
echo " 30 2 * * * /path/to/db_cleanup_cron_fixed.sh auto >> /var/log/cron_ddos.log 2>&1"
echo ""
echo -e "${MAGENTA}Configurazioni cron per pulizie rapide:${NC}"
echo " # Pulizia IP > 1 ora ogni 2 ore"
echo " 0 */2 * * * /path/to/db_cleanup_cron_fixed.sh 1h >> /var/log/ddos_1h.log 2>&1"
echo " # Pulizia IP > 12 ore ogni 6 ore"
echo " 0 */6 * * * /path/to/db_cleanup_cron_fixed.sh 12h >> /var/log/ddos_12h.log 2>&1"
echo ""
echo -e "${YELLOW}Log file:${NC} $LOG_FILE"
;;
*)
log_error "Comando sconosciuto: $1"
echo -e "${RED}❌ Comando sconosciuto. Usa '$0 help' per l'aiuto${NC}"
exit 1
;;
esac
exit_code=$?
# Log finale
if [ $exit_code -eq 0 ]; then
log_success "Script terminato con successo"
else
log_error "Script terminato con errori (exit code: $exit_code)"
fi
exit $exit_code