Random Scripts
Plesk Strace Script
- This is for Plesk to auto Strace php-fpm processes spiking over 80%
touch pleskstrace.sh && chmod +x pleskstrace.sh && nano pleskstrace.sh
./pleskstrace.sh
#!/bin/bash
# Configuration
TOP_PROCESSES=15 # Number of top CPU-consuming processes to consider
CPU_THRESHOLD=10 # Minimum CPU percentage to consider for tracing
SHORT_TIME=10 # Processes running less than this (in seconds) are considered short-lived
MEDIUM_TIME=60 # Processes running less than this (in seconds) are considered medium-duration
DURATION=30 # Duration to run strace (in seconds)
OUTPUT_DIR="/tmp/php-fpm-strace-logs"
TOTAL_RUNTIME=3600 # Total runtime of the script in seconds (default: 1 hour)
CHECK_INTERVAL=60 # Interval between checks in seconds (default: 1 minute)
# Create output directory if it doesn't exist
mkdir -p "$OUTPUT_DIR"
# Function to get top CPU-consuming PHP-FPM processes
get_top_cpu_php_fpm() {
ps aux | grep php-fpm | grep -v grep | sort -nrk 3,3 | head -n $TOP_PROCESSES |
awk -v cpu_threshold=$CPU_THRESHOLD -v short_time=$SHORT_TIME -v medium_time=$MEDIUM_TIME '
function time_to_seconds(time) {
split(time, t, ":")
return t[1]*3600 + t[2]*60 + t[3]
}
function categorize_time(seconds) {
if (seconds < short_time) return "Short (" seconds "s)"
else if (seconds < medium_time) return "Medium (" seconds "s)"
else return "Long (" seconds "s)"
}
{
time_sec = time_to_seconds($11)
category = categorize_time(time_sec)
if ($3 >= cpu_threshold || time_sec >= medium_time)
print $2 "," $3 "," $1 "," $11 "," category "," $NF
}'
}
# Main loop
start_time=$(date +%s)
end_time=$((start_time + TOTAL_RUNTIME))
while [ $(date +%s) -lt $end_time ]; do
echo "$(date): Checking PHP-FPM processes..."
high_cpu_processes=$(get_top_cpu_php_fpm)
if [ -n "$high_cpu_processes" ]; then
echo "$high_cpu_processes" | while IFS=',' read -r pid cpu user time category pool; do
echo "PID: $pid, CPU: $cpu%, User: $user, Running Time: $time ($category), Pool: $pool"
if [[ "$category" == Long* ]] || (( $(echo "$cpu >= 30" | bc -l) )); then
output_file="$OUTPUT_DIR/strace_php-fpm_${pid}_${pool}_$(date +%Y%m%d_%H%M%S).log"
echo "Running strace on PID $pid. Output will be saved to $output_file"
# Run strace in background and kill after DURATION
timeout $DURATION strace -f -e trace=network -p $pid > "$output_file" 2>&1 &
# Wait for strace to finish
wait $!
echo "Strace complete for PID $pid. Log saved to $output_file"
echo "---"
fi
done
else
echo "No PHP-FPM processes currently exceeding CPU threshold of $CPU_THRESHOLD% or medium time threshold of $MEDIUM_TIME seconds"
fi
echo "Waiting for next check..."
sleep $CHECK_INTERVAL
# Check if we've reached the end time
if [ $(date +%s) -ge $end_time ]; then
echo "Total runtime reached. Exiting..."
break
fi
done
echo "Script completed. Check $OUTPUT_DIR for strace logs."
Loadwatch/domlog cross reference (Cpanel)
touch loadspikechech.sh && chmod +x loadspikechech.sh && nano loadspikechech.sh
./loadspikechech.sh
#!/bin/bash
# Configuration
LOG_DIR="/var/log/loadwatch"
DOMLOGS_DIR="/var/log/apache2/domlogs"
CURRENT_DATE=$(date +"%Y-%m-%d")
LOAD_THRESHOLD=5.0
TIME_WINDOW=5
# ANSI colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
BOLD='\033[1m'
analyze_logs() {
local username=$1
local log_time=$2
echo -e "\n${BOLD}${BLUE}═══════════════════════════════════════════════════════════${NC}"
echo -e "${BOLD}${BLUE}ANALYZING USER: $username${NC}"
echo -e "${BOLD}${BLUE}TIME WINDOW: $log_time (±$TIME_WINDOW minutes)${NC}"
echo -e "${BOLD}${BLUE}═══════════════════════════════════════════════════════════${NC}\n"
# Calculate time range once
start_time=$(date -d "$CURRENT_DATE $log_time - $TIME_WINDOW minutes" +"%d/%b/%Y:%H:%M")
end_time=$(date -d "$CURRENT_DATE $log_time + $TIME_WINDOW minutes" +"%d/%b/%Y:%H:%M")
# Find all log files for this user
find "$DOMLOGS_DIR/$username" -type f -name "*log" 2>/dev/null | while read -r logfile; do
echo -e "${BOLD}DOMAIN LOG: $(basename "$logfile")${NC}"
# Use grep directly for efficiency
grep -A1 -B1 "$start_time\|$end_time" "$logfile" > /tmp/matches_$$ 2>/dev/null
if [ -s /tmp/matches_$$ ]; then
total_requests=$(wc -l < /tmp/matches_$$)
unique_ips=$(awk '{print $1}' /tmp/matches_$$ | sort -u | wc -l)
echo -e "\n${BOLD}TRAFFIC SUMMARY:${NC}"
echo "• Total Requests: $total_requests"
echo "• Unique IPs: $unique_ips"
echo -e "\n${BOLD}TOP IP ADDRESSES BY REQUEST COUNT:${NC}"
awk '{print $1}' /tmp/matches_$$ | sort | uniq -c | sort -rn | head -5 | \
while read -r count ip; do
echo -e "• $ip - $count requests"
# Show sample requests for this IP
echo " Sample requests:"
grep "^$ip" /tmp/matches_$$ | head -3 | sed 's/^/ /'
done
echo -e "\n${BOLD}SUSPICIOUS ACTIVITY:${NC}"
if grep -qiE "/(wp-|php|admin|\.env|eval|shell|hack|exploit)" /tmp/matches_$$; then
echo -e "${RED}Found suspicious requests:${NC}"
grep -iE "/(wp-|php|admin|\.env|eval|shell|hack|exploit)" /tmp/matches_$$ | \
head -5 | sed 's/^/• /'
else
echo -e "${GREEN}No obvious malicious patterns detected${NC}"
fi
echo -e "\n${BOLD}HTTP STATUS CODES:${NC}"
awk '{print $9}' /tmp/matches_$$ | sort | uniq -c | sort -rn | \
while read -r count code; do
case $code in
2*) echo -e "${GREEN}• $code: $count requests${NC}" ;;
3*) echo -e "${BLUE}• $code: $count requests${NC}" ;;
4*) echo -e "${YELLOW}• $code: $count requests${NC}" ;;
5*) echo -e "${RED}• $code: $count requests${NC}" ;;
*) echo "• $code: $count requests" ;;
esac
done
echo -e "\n${BOLD}REQUEST RATE ANALYSIS:${NC}"
echo "Requests per minute:"
awk '{print $4}' /tmp/matches_$$ | cut -d: -f2,3 | sort | uniq -c | sort -n
else
echo -e "${YELLOW}No matching entries found in time window${NC}"
fi
echo -e "\n${BOLD}${BLUE}───────────────────────────────────────────────────────────${NC}\n"
rm -f /tmp/matches_$$ 2>/dev/null
done
}
analyze_file() {
local file=$1
if grep -q "load average: [5-9]\|load average: [0-9][0-9]" "$file"; then
echo -e "\n${BOLD}${RED}▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓${NC}"
load_time=$(grep "load average:" "$file" | head -1 | awk '{print $1}')
load_avg=$(grep "load average:" "$file" | head -1 | awk '{print $10 $11 $12}' | tr -d ',')
echo -e "${BOLD}${RED}LOAD SPIKE DETECTED${NC}"
echo -e "Time: $load_time"
echo -e "Load Average: $load_avg"
echo -e "${BOLD}${RED}▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓${NC}\n"
echo -e "${BOLD}HIGH CPU PROCESSES:${NC}"
grep -A15 "PID USER" "$file" | grep -E "^[0-9]+" | \
awk '$9 > 40.0 {printf "• User: %-8s CPU: %5s%% Memory: %5sMB Runtime: %-8s Command: %s\n",
$2, $9, $6, $11, $12}' | sort -k3 -nr
# Process each high-CPU user
grep -A15 "PID USER" "$file" | grep -E "^[0-9]+" | awk '$9 > 40.0 {print $2}' | sort -u | \
while read -r username; do
analyze_logs "$username" "$load_time"
done
fi
}
echo -e "${BOLD}${BLUE}LOAD ANALYSIS REPORT - $CURRENT_DATE${NC}"
echo -e "${BOLD}${BLUE}Looking for load spikes above $LOAD_THRESHOLD${NC}"
echo -e "${BOLD}${BLUE}Analysis window: ±$TIME_WINDOW minutes${NC}\n"
find "$LOG_DIR" -type f -name "${CURRENT_DATE}*.txt" -mmin -60 | sort | while read -r file; do
analyze_file "$file"
done
Cpanel Access log check against AbuseIPDB
touch check_blacklist.sh && chmod +x check_blacklist.sh && nano check_blacklist.sh
./check_blacklist.sh
#!/bin/bash
# Usage: ./check_blacklist.sh <logfile> <api_key>
if [ $# -ne 2 ]; then
echo "Usage: $0 <logfile> <api_key>"
echo "Example: $0 /var/log/access.log your_api_key_here"
exit 1
fi
LOGFILE=$1
API_KEY=$2
if [ ! -f "$LOGFILE" ]; then
echo "Error: Log file $LOGFILE not found!"
exit 1
fi
# Extract IPs and counts
cat $LOGFILE | awk '{print $1}' | sort | uniq -c | sort -rn | while read count ip; do
# Check AbuseIPDB
result=$(curl -s -G https://api.abuseipdb.com/api/v2/check \
--data-urlencode "ipAddress=$ip" \
-d maxAgeInDays=90 \
-d verbose \
-H "Key: $API_KEY" \
-H "Accept: application/json")
# Parse response
abuse_score=$(echo $result | jq -r '.data.abuseConfidenceScore')
if [ "$abuse_score" -gt 0 ]; then
echo "$count $ip - AbuseIPDB Score: $abuse_score%"
fi
done
Usage
./check_blacklist.sh /home/user/access-logs/domain.com-ssl_log APIKEY
Replace the location of the access log and the API key
Sar summarizing 30 days of usage.
touch sar30.sh && chmod +x sar30.sh && nano sar30.sh
./sar30.sh
#!/bin/bash
# Set the month to analyze (default to current month if not specified)
MONTH=${1:-$(date +%m)}
YEAR=${2:-$(date +%Y)}
# Create output directory
OUTPUT_DIR="sar_monthly_report_${MONTH}_${YEAR}"
mkdir -p "$OUTPUT_DIR"
# ANSI color codes
BLUE='\033[0;34m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
BOLD='\033[1m'
# Function to draw a horizontal line
draw_line() {
printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
}
# Function to create a centered header
print_header() {
local title="$1"
local width=${COLUMNS:-$(tput cols)}
local padding=$(( (width - ${#title}) / 2 ))
printf "\n%${padding}s${BOLD}%s${NC}%${padding}s\n" '' "$title" ''
draw_line
}
# Function to get the previous month and year
get_prev_month() {
local month=$1
local year=$2
if [ "$month" -eq 1 ]; then
echo "$((year-1)) 12"
else
echo "$year $((month-1))"
fi
}
# Function to extract and format daily averages
get_daily_stats() {
local day=$1
local month=$2
local year=$3
local padded_day=$(printf "%02d" $day)
local padded_month=$(printf "%02d" $month)
local date="${year}-${padded_month}-${padded_day}"
local log_file="/var/log/sa/sa${padded_day}"
# CPU Usage
local cpu_stats=$(sar -f "$log_file" -u | awk '
BEGIN {sum=0; count=0}
/^Average/ {
if (NF == 8) {
sum=$8; count++
}
}
END {
if (count > 0) printf "%.2f", 100-(sum/count)
}')
# Memory Usage - excludes cache/buffers so it reflects real pressure.
# Real "used" = total - available (kbavail); falls back to
# kbmemused - buffers - cached on older sysstat without kbavail.
#
# Columns are located by header NAME, but indexed RELATIVE to kbmemfree.
# This matters because the header row may carry extra leading tokens
# (e.g. a "12:00:01 AM" timestamp in 12-hour locales) that the "Average:"
# row does not, which would otherwise shift every column by one and
# produce nonsense (negative) values.
local mem_stats=$(sar -f "$log_file" -r | awk '
/kbmemfree/ {
for (i=1;i<=NF;i++) { rel[$i]=i; if ($i=="kbmemfree") base=i }
have=1; next
}
/^Average/ {
if (!have) next
free = $(2 + rel["kbmemfree"] - base)
used = $(2 + rel["kbmemused"] - base)
total = free + used
if ("kbavail" in rel)
realused = total - $(2 + rel["kbavail"] - base)
else
realused = used - $(2 + rel["kbbuffers"] - base) - $(2 + rel["kbcached"] - base)
sum_real += realused; sum_total += total; count++
}
END {
if (count > 0)
printf "%.2f,%.2f", (sum_real/count)/1048576, (sum_real/sum_total)*100
}')
# I/O Statistics - disk throughput in MB/s from "sar -b".
# bread/s and bwrtn/s are blocks read/written per second; sar counts
# 512-byte blocks, so MB/s = blocks/s / 2048.
# Columns are located by name and anchored relative to tps, so the
# discard columns (dtps/bdscd/s) added in newer sysstat don't shift them.
local io_stats=$(sar -f "$log_file" -b | awk '
/bread/ {
for (i=1;i<=NF;i++) { rel[$i]=i; if ($i=="tps") base=i }
have=1; next
}
/^Average/ {
if (!have) next
sum_read += $(2 + rel["bread/s"] - base)
sum_write += $(2 + rel["bwrtn/s"] - base)
sum_rtps += $(2 + rel["rtps"] - base)
sum_wtps += $(2 + rel["wtps"] - base)
count++
}
END {
if (count > 0)
printf "%.2f,%.2f,%.2f,%.2f",
(sum_read/count)/2048, (sum_write/count)/2048,
sum_rtps/count, sum_wtps/count
}')
# Output in CSV format for later processing
echo "${date},${cpu_stats},${mem_stats},${io_stats}"
}
print_table_header() {
printf "\n${BOLD}%-12s | %-15s | %-20s | %-23s | %-15s${NC}\n" "Date" "CPU Used %" "Memory (GB/Used%)" "Disk MB/s (read/write)" "IOPS (rd/wr)"
draw_line
}
# Get the number of days needed from the current month
days_in_month=$(cal $MONTH $YEAR | awk 'NF {DAYS = $NF}; END {print DAYS}')
CURRENT_MONTH=$(date +%m)
CURRENT_YEAR=$(date +%Y)
CURRENT_DAY=$(date +%d)
# Create temporary file for storing daily stats
TEMP_FILE=$(mktemp)
print_header "System Performance Report for ${MONTH}/${YEAR}"
# Get previous month details for rollover
read PREV_YEAR PREV_MONTH <<< $(get_prev_month $MONTH $YEAR)
PREV_MONTH_DAYS=$(cal $PREV_MONTH $PREV_YEAR | awk 'NF {DAYS = $NF}; END {print DAYS}')
# Collect data
for day in $(seq 1 $days_in_month); do
padded_day=$(printf "%02d" $day)
# Check if we need to use current month's data or previous month's
if [ "$MONTH" -eq "$CURRENT_MONTH" ] && [ "$YEAR" -eq "$CURRENT_YEAR" ] && [ "$day" -gt "$CURRENT_DAY" ]; then
# Calculate the corresponding day from previous month
prev_month_day=$((PREV_MONTH_DAYS - (days_in_month - day)))
if [ -f "/var/log/sa/sa$(printf "%02d" $prev_month_day)" ]; then
get_daily_stats $prev_month_day $PREV_MONTH $PREV_YEAR >> "$TEMP_FILE"
fi
else
if [ -f "/var/log/sa/sa${padded_day}" ]; then
get_daily_stats $day $MONTH $YEAR >> "$TEMP_FILE"
fi
fi
done
# Sort the data by date and save to a new temp file
SORTED_TEMP_FILE=$(mktemp)
sort "$TEMP_FILE" > "$SORTED_TEMP_FILE"
# Print daily summary
print_header "Daily Statistics"
print_table_header
# Process and display daily stats
while IFS=, read -r date cpu_used mem_gb mem_percent io_read io_write io_rtps io_wtps; do
printf "%-12s | ${GREEN}%6.2f%%${NC}%8s | %-8.2f GB (${GREEN}%-6.1f%%${NC}) | %7.2f R / %7.2f W | %6.1f / %-6.1f\n" \
"$date" "$cpu_used" "" "$mem_gb" "$mem_percent" "$io_read" "$io_write" "$io_rtps" "$io_wtps"
done < "$SORTED_TEMP_FILE"
# Clean up the sorted temp file
rm "$SORTED_TEMP_FILE"
# Calculate and display monthly averages
print_header "Monthly Averages"
awk -F, '
BEGIN {
cpu_sum = mem_gb_sum = mem_pct_sum = io_read_sum = io_write_sum = io_rtps_sum = io_wtps_sum = count = 0
}
{
cpu_sum += $2
mem_gb_sum += $3
mem_pct_sum += $4
io_read_sum += $5
io_write_sum += $6
io_rtps_sum += $7
io_wtps_sum += $8
count++
}
END {
if (count > 0) {
printf "\n%-20s: %.2f%%\n", "Average CPU Usage", cpu_sum/count
printf "%-20s: %.2f GB (%.1f%%)\n", "Average Memory Usage", \
mem_gb_sum/count, mem_pct_sum/count
printf "%-20s: %.2f MB/s read, %.2f MB/s write\n", "Average Disk I/O", \
io_read_sum/count, io_write_sum/count
printf "%-20s: %.1f read/s, %.1f write/s\n", "Average IOPS", \
io_rtps_sum/count, io_wtps_sum/count
}
}' "$TEMP_FILE"
# Save formatted report to file (before cleanup, so the file isn't empty)
{
echo "System Performance Report for ${MONTH}/${YEAR}"
echo "Generated on $(date)"
echo "=================================================="
sort "$TEMP_FILE" | column -t -s,
} > "${OUTPUT_DIR}/formatted_report.txt"
# Clean up
rm "$TEMP_FILE"
echo -e "\nReport saved to ${OUTPUT_DIR}/formatted_report.txt"
Quick log error overview
touch logcheck.sh && chmod +x logcheck.sh && nano logcheck.sh
./logcheck.sh
#!/bin/bash
# Configuration
LOG_DIRS=(
"/var/log"
"/var/log/syslog"
"/var/log/nginx"
"/var/log/apache2"
"/var/log/mysql"
"/var/log/postgresql"
"/opt/*/logs"
"/var/log/containers"
)
# ANSI color codes
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color
# Error patterns to search for
declare -a PATTERNS=(
"\[error\]"
"PHP Fatal error"
"PHP Warning"
"Exception"
"failed"
"failure"
"error"
"critical"
"fatal"
"denied"
"refused"
)
# Patterns to exclude (noise reduction)
declare -a EXCLUDE_PATTERNS=(
"Sending HTTP request to /api/task_manager/v2/consumers.*CPS_SmartPlan"
"INFO:.*client-tm.*CPS_SmartPlan"
)
# Function to check if a command exists
command_exists() {
command -v "$1" >/dev/null 2>&1
}
# Function to print usage
print_usage() {
echo "Usage: $0 [-d days] [-p pattern] [-l location] [-h]"
echo " -d: Number of days to look back (default: 1)"
echo " -p: Additional pattern to search for"
echo " -l: Specific log location to search (default: predefined directories)"
echo " -h: Show this help message"
exit 1
}
# Function to print with timestamp
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}
# Function to check file permissions
check_readable() {
if [[ ! -r "$1" ]]; then
echo -e "${YELLOW}Warning: No permission to read $1${NC}"
return 1
fi
return 0
}
# Function to get log files modified within specified days
get_recent_logs() {
local days=$1
local dir=$2
if command_exists find; then
find "$dir" -type f -mtime -"$days" \( -name "*.log" -o -name "*.err" -o -name "syslog" \) 2>/dev/null
else
# Fallback if find is not available
ls -t "$dir"/*.log "$dir"/*.err "$dir"/syslog 2>/dev/null | head -n 100
fi
}
# Parse command line arguments
DAYS=1
ADDITIONAL_PATTERN=""
SPECIFIC_LOCATION=""
while getopts "d:p:l:h" opt; do
case $opt in
d) DAYS="$OPTARG" ;;
p) ADDITIONAL_PATTERN="$OPTARG"
PATTERNS+=("$ADDITIONAL_PATTERN") ;;
l) SPECIFIC_LOCATION="$OPTARG" ;;
h) print_usage ;;
?) print_usage ;;
esac
done
# Create temporary files
TEMP_DIR=$(mktemp -d)
RESULTS_FILE="$TEMP_DIR/log_results.txt"
ERROR_FILE="$TEMP_DIR/log_errors.txt"
# Cleanup function
cleanup() {
rm -rf "$TEMP_DIR"
}
trap cleanup EXIT
# Function to check system metrics
check_system_metrics() {
echo -e "\n${GREEN}=== System Metrics ===${NC}"
# Check disk space
if command_exists df; then
echo -e "\n${YELLOW}Disk Usage:${NC}"
df -h | grep -vE '^tmpfs|^devtmpfs|^udev'
fi
# Check memory
if [[ -f /proc/meminfo ]]; then
echo -e "\n${YELLOW}Memory Usage:${NC}"
free -h 2>/dev/null || grep -E "MemTotal|MemFree|MemAvailable" /proc/meminfo
fi
# Check load average
if [[ -f /proc/loadavg ]]; then
echo -e "\n${YELLOW}Load Average:${NC}"
cat /proc/loadavg
fi
}
# Main log checking function
check_logs() {
local search_dirs=("${LOG_DIRS[@]}")
[[ -n "$SPECIFIC_LOCATION" ]] && search_dirs=("$SPECIFIC_LOCATION")
echo -e "${GREEN}=== Checking logs for the last $DAYS day(s) ===${NC}"
for dir in "${search_dirs[@]}"; do
# Skip if directory doesn't exist or isn't readable
[[ ! -d "$dir" ]] && continue
[[ ! -r "$dir" ]] && continue
log "Checking directory: $dir"
while IFS= read -r log_file; do
[[ ! -f "$log_file" ]] && continue
check_readable "$log_file" || continue
log "Analyzing: $log_file"
# Create pattern string for grep
pattern_string=$(printf "|%s" "${PATTERNS[@]}")
pattern_string=${pattern_string:1}
# Search for patterns and format output
# Search for patterns and exclude noise
if command_exists zgrep && [[ "$log_file" =~ \.gz$ ]]; then
zgrep -iE "$(echo "${PATTERNS[@]}" | tr ' ' '|')" "$log_file" 2>/dev/null | \
grep -vE "$(echo "${EXCLUDE_PATTERNS[@]}" | tr ' ' '|')" >> "$RESULTS_FILE" || true
else
grep -iE "$(echo "${PATTERNS[@]}" | tr ' ' '|')" "$log_file" 2>/dev/null | \
grep -vE "$(echo "${EXCLUDE_PATTERNS[@]}" | tr ' ' '|')" >> "$RESULTS_FILE" || true
fi
done < <(get_recent_logs "$DAYS" "$dir")
done
}
# Generate report
generate_report() {
echo -e "\n${GREEN}=== Log Analysis Report ===${NC}"
if [[ -s "$RESULTS_FILE" ]]; then
echo -e "\n${YELLOW}Found issues:${NC}"
# Count occurrences of each pattern
for pattern in "${PATTERNS[@]}"; do
# Simple grep with wc for counting
if count=$(grep -ic "$pattern" "$RESULTS_FILE" 2>/dev/null) && [ -n "$count" ]; then
if [ "$count" -gt 0 ]; then
echo -e "${RED}$pattern: $count occurrences${NC}"
fi
fi
done
# Process results to show top 10 most frequent error types
echo -e "\n${YELLOW}Top 10 Most Frequent Errors:${NC}"
{
echo "=== Error Summary ==="
awk '
function extract_error_type(line) {
# HTTP Status code errors
if (line ~ /SendHttpRequest ERROR: [0-9]+/) {
status = line
if (match(line, /ERROR: [0-9]+/)) {
status = substr(line, RSTART+7, RLENGTH-7)
}
return "HTTP " status " Error"
}
# Facebook errors
else if (line ~ /FacebookAuthenticationException/) {
return "Facebook Authentication Error"
}
# PHP Fatal errors
else if (line ~ /PHP Fatal error:.*Class .AuthorizeNet. not found/) {
return "AuthorizeNet Class Missing"
}
else if (line ~ /PHP Fatal error:.*memory.*exhausted/) {
return "PHP Memory Limit Exceeded"
}
else if (line ~ /PHP Fatal error/) {
return "PHP Fatal Error (Other)"
}
# File not found errors
else if (line ~ /No such file or directory/) {
return "404 File Not Found"
}
# Database errors
else if (line ~ /MySQL|mysqli|PDO|Database/) {
return "Database Error"
}
# Authentication errors
else if (line ~ /Authentication failed|Invalid credentials|unauthorized|permission denied/i) {
return "Authentication Error"
}
# Connection errors
else if (line ~ /Connection timed out|Connection refused/) {
return "Connection Error"
}
# Parse specific error messages
else if (match(line, /ERROR:? [A-Za-z ]+/)) {
return substr(line, RSTART+7, RLENGTH-7) " Error"
}
else if (line ~ /\[error\]/) {
return "Nginx Error"
}
return "Other Error"
}
{
error_type = extract_error_type($0)
count[error_type]++
if (!(error_type in first_occurrence)) {
first_occurrence[error_type] = $0
}
}
END {
print "\nError Type Counts:"
print "=================="
# Sort by count in descending order
PROCINFO["sorted_in"] = "@val_num_desc"
i = 0
for (type in count) {
if (++i <= 10) {
printf "\n%s: %d occurrences\n", type, count[type]
printf "Example: %s\n", first_occurrence[type]
print "===================="
}
}
}
' "$RESULTS_FILE"
} | tee "$TEMP_DIR/error_summary.txt"
else
echo -e "${GREEN}No issues found in logs${NC}"
fi
if [[ -s "$ERROR_FILE" ]]; then
echo -e "\n${RED}Errors encountered during analysis:${NC}"
cat "$ERROR_FILE"
fi
}
# Main execution
main() {
# Check if running as root, warn if not
if [[ $EUID -ne 0 ]]; then
echo -e "${YELLOW}Warning: Not running as root. Some logs may be inaccessible.${NC}"
fi
check_system_metrics
check_logs
generate_report
}
main
Mysql slow log summary
touch mysql-slow-log-analyzer.sh && chmod +x mysql-slow-log-analyzer.sh && nano mysql-slow-log-analyzer.sh
./mysql-slow-log-analyzer.sh
#!/bin/bash
# MySQL/MariaDB Slow Query Log Analyzer
# This script analyzes a MySQL/MariaDB slow query log file and provides a summary of the slowest queries,
# including counts, average execution times, and other useful metrics.
# Configuration variables - modify these as needed
DEFAULT_SLOW_LOG="/var/lib/mysql/slow.log" # Default path to MySQL slow query log
DEFAULT_TOP_N=10 # Default number of top queries to show
# Parse command line arguments
if [ $# -ge 1 ]; then
SLOW_LOG=$1
else
# Try to auto-detect MySQL slow log location
if [ -f "$DEFAULT_SLOW_LOG" ]; then
SLOW_LOG=$DEFAULT_SLOW_LOG
echo "Using default slow log path: $SLOW_LOG"
else
# Try common locations
COMMON_PATHS=(
"/var/log/mysql/mysql-slow.log"
"/var/log/mysql-slow.log"
"/var/lib/mysql/$(hostname)-slow.log"
"/var/log/mysqld-slow.log"
)
for path in "${COMMON_PATHS[@]}"; do
if [ -f "$path" ]; then
SLOW_LOG=$path
echo "Auto-detected slow log path: $SLOW_LOG"
break
fi
done
# If still not found
if [ -z "$SLOW_LOG" ]; then
echo "Error: Slow query log not found!"
echo "Please specify the log file path:"
echo "Usage: $0 <slow-query-log-file> [number-of-results]"
echo "Example: $0 /var/lib/mysql/slow.log 10"
echo ""
echo "Or edit the DEFAULT_SLOW_LOG variable in this script."
exit 1
fi
fi
fi
TOP_N=${2:-$DEFAULT_TOP_N} # Use command-line argument or default
# Check if the log file exists and is readable
if [ ! -f "$SLOW_LOG" ]; then
echo "Error: Log file '$SLOW_LOG' not found!"
exit 1
fi
if [ ! -r "$SLOW_LOG" ]; then
echo "Error: Cannot read log file '$SLOW_LOG' - permission denied!"
exit 1
fi
# Check if the file is empty
if [ ! -s "$SLOW_LOG" ]; then
echo "Error: Log file '$SLOW_LOG' is empty!"
exit 1
fi
# Display file stats and preview
FILE_SIZE=$(du -h "$SLOW_LOG" | cut -f1)
LINE_COUNT=$(wc -l < "$SLOW_LOG")
echo "Log file size: $FILE_SIZE (${LINE_COUNT} lines)"
echo ""
echo "Log file preview (first 5 lines):"
echo "--------------------------------"
head -n 5 "$SLOW_LOG"
echo "--------------------------------"
echo "=== MySQL/MariaDB Slow Query Log Analysis ==="
echo "Analyzing: $SLOW_LOG"
echo "Showing top $TOP_N queries"
echo "================================="
# Detect the log format (MySQL vs MariaDB)
MYSQL_FORMAT=$(grep -c "^# Query_time:" "$SLOW_LOG")
MARIADB_FORMAT=$(grep -c "^# Time:" "$SLOW_LOG")
# Create a temporary directory
TEMP_DIR=$(mktemp -d)
QUERIES_FILE="$TEMP_DIR/queries.txt"
SUMMARY_FILE="$TEMP_DIR/summary.txt"
# Function to clean up temporary files
cleanup() {
rm -rf "$TEMP_DIR"
}
# Register the cleanup function for script exit
trap cleanup EXIT
echo "Extracting and parsing queries..."
# Choose the appropriate parsing approach based on detected format
if [ "$MARIADB_FORMAT" -gt 0 ]; then
echo "Detected MariaDB slow query log format"
# Get blocks between Time entries, preserving them for processing
awk '/^# Time:/ {if (NR!=1) {print ""; print $0} else print $0; next} {print}' "$SLOW_LOG" > "$TEMP_DIR/blocks.txt"
# Extract the actual queries from the blocks
awk '
BEGIN {
in_block = 0
query_time = 0
lock_time = 0
rows_sent = 0
rows_examined = 0
query = ""
}
/^# Time:/ {
# Process previous block if we have a query
if (in_block && query != "") {
printf "QUERY_TIME: %f\n", query_time
printf "LOCK_TIME: %f\n", lock_time
printf "ROWS_SENT: %d\n", rows_sent
printf "ROWS_EXAMINED: %d\n", rows_examined
printf "QUERY: %s\n", query
printf "BLOCK_END\n\n"
}
# Start a new block
in_block = 1
query_time = 0
lock_time = 0
rows_sent = 0
rows_examined = 0
query = ""
print "BLOCK_START"
print $0
}
/^# Query_time:/ && in_block {
match($0, /Query_time: ([0-9.]+)/, qt)
if (qt[1] != "") query_time = qt[1]
match($0, /Lock_time: ([0-9.]+)/, lt)
if (lt[1] != "") lock_time = lt[1]
match($0, /Rows_sent: ([0-9]+)/, rs)
if (rs[1] != "") rows_sent = rs[1]
match($0, /Rows_examined: ([0-9]+)/, re)
if (re[1] != "") rows_examined = re[1]
}
!/^#/ && in_block {
if ($0 != "") {
if (query == "")
query = $0
else
query = query " " $0
}
}
END {
# Process the last block
if (in_block && query != "") {
printf "QUERY_TIME: %f\n", query_time
printf "LOCK_TIME: %f\n", lock_time
printf "ROWS_SENT: %d\n", rows_sent
printf "ROWS_EXAMINED: %d\n", rows_examined
printf "QUERY: %s\n", query
printf "BLOCK_END\n"
}
}
' "$TEMP_DIR/blocks.txt" > "$TEMP_DIR/extracted.txt"
# Process the extracted data for analysis
awk '
BEGIN {
in_block = 0
query_time = 0
lock_time = 0
rows_sent = 0
rows_examined = 0
query = ""
}
/^BLOCK_START/ {
in_block = 1
}
/^QUERY_TIME:/ && in_block {
query_time = $2
}
/^LOCK_TIME:/ && in_block {
lock_time = $2
}
/^ROWS_SENT:/ && in_block {
rows_sent = $2
}
/^ROWS_EXAMINED:/ && in_block {
rows_examined = $2
}
/^QUERY:/ && in_block {
query = substr($0, 7)
# Skip just database selection if possible
if (query ~ /^use /) {
# Mark this as potentially unimportant
is_use_only = 1
} else {
is_use_only = 0
}
}
/^BLOCK_END/ && in_block {
if (query != "") {
# Skip pure "use" statements only if we have other queries
if (!is_use_only || query_count == 0) {
# Normalize the query for fingerprinting
normalized = query
gsub(/[0-9]+/, "N", normalized)
gsub(/'"'"'[^'"'"']*'"'"'/, "S", normalized)
gsub(/"[^"]*"/, "S", normalized)
# Store data for this query type
queries[normalized] = query
counts[normalized]++
total_time[normalized] += query_time
if (query_time > max_time[normalized])
max_time[normalized] = query_time
if (lock_time > max_lock[normalized])
max_lock[normalized] = lock_time
total_rows_sent[normalized] += rows_sent
total_rows_examined[normalized] += rows_examined
query_count++
}
}
in_block = 0
}
END {
# Output summary for each unique query
for (q in queries) {
if (counts[q] > 0) {
avg_time = total_time[q] / counts[q]
avg_rows_sent = total_rows_sent[q] / counts[q]
avg_rows_examined = total_rows_examined[q] / counts[q]
rows_ratio = avg_rows_examined > 0 ? avg_rows_sent / avg_rows_examined : 0
printf "QUERY_FINGERPRINT: %s\n", q
printf "COUNT: %d\n", counts[q]
printf "TOTAL_TIME: %.6f\n", total_time[q]
printf "AVG_TIME: %.6f\n", avg_time
printf "MAX_TIME: %.6f\n", max_time[q]
printf "MAX_LOCK: %.6f\n", max_lock[q]
printf "AVG_ROWS_SENT: %.2f\n", avg_rows_sent
printf "AVG_ROWS_EXAMINED: %.2f\n", avg_rows_examined
printf "ROWS_RATIO: %.4f\n", rows_ratio
printf "EXAMPLE: %s\n", queries[q]
printf "---END_QUERY---\n\n"
}
}
}
' "$TEMP_DIR/extracted.txt" > "$QUERIES_FILE"
else
echo "No standard log format detected. Attempting general query extraction..."
# Extract what look like SQL queries - more generic approach
grep -n -i -A 5 -B 2 -E "^(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER) " "$SLOW_LOG" > "$TEMP_DIR/raw_queries.txt"
# Fall back to looking for any lines that aren't log headers
if [ ! -s "$TEMP_DIR/raw_queries.txt" ]; then
echo "Trying alternative extraction method..."
grep -v "^#" "$SLOW_LOG" | grep -v "^$" > "$TEMP_DIR/raw_queries.txt"
fi
# If we still don't have anything, show an error
if [ ! -s "$TEMP_DIR/raw_queries.txt" ]; then
echo "Error: Could not extract any queries from the log file."
echo "This might not be a properly formatted MySQL/MariaDB slow query log."
echo ""
echo "Debug information:"
echo "Total lines in log: $LINE_COUNT"
echo "Lines containing 'SELECT': $(grep -c -i "SELECT" "$SLOW_LOG")"
echo "Lines containing 'INSERT': $(grep -c -i "INSERT" "$SLOW_LOG")"
echo "Lines containing 'Query_time:': $(grep -c "Query_time:" "$SLOW_LOG")"
exit 1
fi
echo "Found $(wc -l < "$TEMP_DIR/raw_queries.txt") potential query-related lines"
echo "Format not fully supported - analysis may be incomplete"
# Basic summary of the extracted data
echo "Most common query types found:" > "$QUERIES_FILE"
grep -i -o -E "^(SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP) " "$TEMP_DIR/raw_queries.txt" | sort | uniq -c | sort -nr >> "$QUERIES_FILE"
echo "Sample of extracted queries:" >> "$QUERIES_FILE"
head -n 20 "$TEMP_DIR/raw_queries.txt" >> "$QUERIES_FILE"
fi
# Check if we extracted any queries
if [ ! -s "$QUERIES_FILE" ]; then
echo "Warning: No queries were successfully extracted from the log."
echo "This could mean that:"
echo " 1. There are no slow queries in the log yet"
echo " 2. The log format is not supported by this script"
echo " 3. The file might not be a slow query log"
echo ""
echo "You might want to try:"
echo " - Checking MySQL/MariaDB slow query log settings"
echo " - Running a few slow queries to generate log entries"
echo " - Using pt-query-digest from Percona Toolkit instead"
exit 0
fi
echo "Generating summary by total execution time..."
# Sort queries by total time and create a summary
awk '
BEGIN {
query_count = 0
in_query = 0
printf "%-5s %-10s %-10s %-10s %-10s %-15s %-15s %-10s\n",
"RANK", "COUNT", "TOTAL(s)", "AVG(s)", "MAX(s)", "ROWS_SENT", "ROWS_EXAM", "RATIO"
printf "%-5s %-10s %-10s %-10s %-10s %-15s %-15s %-10s\n",
"----", "-----", "--------", "------", "------", "---------", "---------", "-----"
}
/^QUERY_FINGERPRINT: / {
fingerprint = substr($0, 20)
in_query = 1
}
/^COUNT: / && in_query { count = $2 }
/^TOTAL_TIME: / && in_query { total_time = $2 }
/^AVG_TIME: / && in_query { avg_time = $2 }
/^MAX_TIME: / && in_query { max_time = $2 }
/^AVG_ROWS_SENT: / && in_query { avg_rows_sent = $2 }
/^AVG_ROWS_EXAMINED: / && in_query { avg_rows_examined = $2 }
/^ROWS_RATIO: / && in_query { rows_ratio = $2 }
/^EXAMPLE: / && in_query {
example = substr($0, 9)
# Truncate example query for summary
if (length(example) > 50) {
example = substr(example, 1, 47) "..."
}
}
/^---END_QUERY---/ && in_query {
query_count++
# Store the data for sorting
data[query_count, "fingerprint"] = fingerprint
data[query_count, "count"] = count
data[query_count, "total_time"] = total_time
data[query_count, "avg_time"] = avg_time
data[query_count, "max_time"] = max_time
data[query_count, "avg_rows_sent"] = avg_rows_sent
data[query_count, "avg_rows_examined"] = avg_rows_examined
data[query_count, "rows_ratio"] = rows_ratio
data[query_count, "example"] = example
# Store the sort key
sort_keys[query_count] = total_time
in_query = 0
}
END {
# Sort by total time (descending)
if (query_count > 0) {
# Create a sorted index
for (i = 1; i <= query_count; i++) {
sorted_indices[i] = i
}
# Bubble sort the indices based on total_time values
for (i = 1; i <= query_count; i++) {
for (j = 1; j <= query_count - i; j++) {
if (sort_keys[sorted_indices[j]] < sort_keys[sorted_indices[j+1]]) {
# Swap
temp = sorted_indices[j]
sorted_indices[j] = sorted_indices[j+1]
sorted_indices[j+1] = temp
}
}
}
# Print the entries
for (i = 1; i <= query_count; i++) {
idx = sorted_indices[i]
printf "%-5d %-10d %-10.2f %-10.4f %-10.4f %-15.2f %-15.2f %-10.4f\n",
i,
data[idx, "count"],
data[idx, "total_time"],
data[idx, "avg_time"],
data[idx, "max_time"],
data[idx, "avg_rows_sent"],
data[idx, "avg_rows_examined"],
data[idx, "rows_ratio"]
printf "QUERY: %s\n\n", data[idx, "example"]
}
}
}
' "$QUERIES_FILE" > "$SUMMARY_FILE"
# Output the top N queries by total time
echo "Top $TOP_N queries by total execution time:"
echo "-------------------------------------------"
if [ -s "$SUMMARY_FILE" ]; then
head -n $((TOP_N * 3)) "$SUMMARY_FILE"
echo ""
echo "Detailed analysis of top $TOP_N queries:"
echo "----------------------------------------"
# Output detailed information for the top N queries
grep -A 1 "^QUERY_FINGERPRINT: " "$QUERIES_FILE" | grep -B 1 "^COUNT: " | head -n $((TOP_N * 2)) | grep "^QUERY_FINGERPRINT: " | cut -d' ' -f2- | while read -r fingerprint; do
# Extract and display full information for this query
awk -v fp="$fingerprint" '
BEGIN { in_query = 0; print_query = 0; query_num = 0; }
/^QUERY_FINGERPRINT: / {
if ($0 == "QUERY_FINGERPRINT: " fp) {
in_query = 1
print_query = 1
print "\n==== QUERY #" ++query_num " ===="
} else {
in_query = 0
}
}
{
if (in_query && print_query) {
if (/^EXAMPLE: /) {
print "QUERY: " substr($0, 9)
} else if (!/^QUERY_FINGERPRINT: /) {
print
}
}
}
/^---END_QUERY---/ {
if (in_query && print_query) {
in_query = 0
print_query = 0
}
}
' "$QUERIES_FILE"
done
# Provide additional statistics
echo ""
echo "Overall Statistics:"
echo "------------------"
TOTAL_QUERIES=$(grep -c "^QUERY_FINGERPRINT: " "$QUERIES_FILE" || echo "0")
UNIQUE_QUERIES=$(grep "^QUERY_FINGERPRINT: " "$QUERIES_FILE" | sort | uniq | wc -l || echo "0")
TOTAL_TIME=$(awk '/^TOTAL_TIME: / {sum += $2} END {print sum}' "$QUERIES_FILE" || echo "0")
# Check if we have any queries before calculating average time
if [ "$TOTAL_QUERIES" -gt 0 ]; then
AVG_TIME=$(awk '/^AVG_TIME: / {sum += $2; count++} END {print sum/count}' "$QUERIES_FILE")
echo "Total query executions: $TOTAL_QUERIES"
echo "Unique query patterns: $UNIQUE_QUERIES"
echo "Total execution time: ${TOTAL_TIME}s"
echo "Average query time: ${AVG_TIME}s"
else
echo "No slow queries found in the log."
fi
else
echo "No analyzable queries found in the log."
fi
echo ""
echo "Recommendations:"
echo "---------------"
echo "1. Examine queries with high execution times and optimize them"
echo "2. Look for queries with high rows_examined to rows_sent ratios (inefficient data retrieval)"
echo "3. Check for queries that appear frequently with moderate execution times"
echo "4. Consider adding indexes for queries examining many rows"
echo ""
echo "For more detailed analysis, consider using pt-query-digest from Percona Toolkit"
Live Netstat ABuseIPDB check
touch live_ip_monitor.sh && chmod +x live_ip_monitor.sh && nano live_ip_monitor.sh
./live_ip_monitor.sh AbuseIPDB_API_Key
#!/bin/bash
# Usage: ./live_ip_monitor.sh <api_key> [refresh_seconds]
# Example: ./live_ip_monitor.sh your_api_key_here 2
if [ $# -lt 1 ]; then
echo "Usage: $0 <api_key> [refresh_seconds]"
echo "Example: $0 your_api_key_here 2"
exit 1
fi
# === CONFIGURABLE SETTINGS ===
# Your AbuseIPDB API key (from command line)
API_KEY=$1
# Refresh rate in seconds (default: 2)
REFRESH_RATE=2
if [ ! -z "$2" ]; then
REFRESH_RATE=$2
fi
# Number of top IPs to display
TOP_IPS=100
# Number of ports to display in the connections summary
TOP_PORTS=10
# Display port connections section? (1=yes, 0=no)
SHOW_PORTS=1
# Display critical IPs in red? (1=yes, 0=no)
USE_COLORS=1
# Mark active connections with an asterisk? (1=yes, 0=no)
MARK_ACTIVE=1
# === END OF CONFIGURABLE SETTINGS ===
# Create a directory for our cache files
CACHE_DIR="/tmp/ip_monitor_cache"
mkdir -p $CACHE_DIR
# Create our counts file
COUNTS_FILE="$CACHE_DIR/cumulative_counts.txt"
touch $COUNTS_FILE
# Function to check an IP with AbuseIPDB (only runs once per IP)
check_ip() {
local ip=$1
local cache_file="$CACHE_DIR/${ip}_abuse.txt"
# Only check if we haven't already
if [ ! -f "$cache_file" ]; then
result=$(curl -s -G https://api.abuseipdb.com/api/v2/check \
--data-urlencode "ipAddress=$ip" \
-d maxAgeInDays=90 \
-d verbose \
-H "Key: $API_KEY" \
-H "Accept: application/json")
# Parse response
abuse_score=$(echo $result | jq -r '.data.abuseConfidenceScore')
country=$(echo $result | jq -r '.data.countryCode')
# Handle null values
if [ "$abuse_score" = "null" ] || [ -z "$abuse_score" ]; then
abuse_score=0
fi
if [ "$country" = "null" ] || [ -z "$country" ]; then
country="??"
fi
# Save to cache file
echo "$abuse_score $country" > "$cache_file"
fi
# Read from cache file
read abuse_score country < "$cache_file"
echo "$abuse_score $country"
}
# Function to get service name for common ports
get_service_name() {
local port=$1
case $port in
21) echo "FTP" ;;
22) echo "SSH" ;;
25) echo "SMTP" ;;
53) echo "DNS" ;;
80) echo "HTTP" ;;
110) echo "POP3" ;;
143) echo "IMAP" ;;
443) echo "HTTPS" ;;
465) echo "SMTPS" ;;
587) echo "SMTP" ;;
993) echo "IMAPS" ;;
995) echo "POP3S" ;;
3306) echo "MySQL" ;;
5432) echo "PostgreSQL" ;;
8080) echo "HTTP-ALT" ;;
8443) echo "HTTPS-ALT" ;;
*) echo "" ;;
esac
}
# Main monitoring loop
while true; do
# Clear screen
clear
echo "LIVE NETSTAT MONITORING WITH ABUSEIPDB CHECKING"
echo "==========================================="
echo "Press Ctrl+C to exit"
echo "==========================================="
echo "TOP $TOP_IPS CONNECTING IPs (CUMULATIVE):"
echo "-------------------"
# Get current active connections
netstat -tn | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | grep -v -E '^(10\.|172\.1[6-9]\.|172\.2[0-9]\.|172\.3[0-1]\.|192\.168\.|127\.)' | sort > "$CACHE_DIR/current_ips.txt"
# Update cumulative counts
while read ip; do
count=$(grep -c "^$ip$" "$CACHE_DIR/current_ips.txt")
if [ $count -gt 0 ]; then
existing=$(grep "^$ip " $COUNTS_FILE 2>/dev/null)
if [ -z "$existing" ]; then
echo "$ip $count" >> $COUNTS_FILE
else
current=$(echo "$existing" | awk '{print $2}')
new_count=$((current + count))
# Use a temp file to avoid sed issues on some systems
grep -v "^$ip " $COUNTS_FILE > "$CACHE_DIR/temp_counts.txt"
echo "$ip $new_count" >> "$CACHE_DIR/temp_counts.txt"
mv "$CACHE_DIR/temp_counts.txt" $COUNTS_FILE
fi
fi
done < <(sort -u "$CACHE_DIR/current_ips.txt")
# Display top IPs
sort -k2 -nr $COUNTS_FILE | head -$TOP_IPS | while read ip count; do
# Check if currently active
if [ $MARK_ACTIVE -eq 1 ]; then
if grep -q "^$ip$" "$CACHE_DIR/current_ips.txt"; then
active="*"
else
active=" "
fi
else
active=" "
fi
# Get abuse info (cached)
read abuse_score country < <(check_ip $ip)
# Format output
if [ $USE_COLORS -eq 1 ]; then
if [ "$abuse_score" -gt 80 ]; then
echo -e "\e[1;31m$active $count $ip - [$country] CRITICAL: AbuseIPDB Score: $abuse_score%\e[0m"
elif [ "$abuse_score" -gt 50 ]; then
echo -e "\e[1;33m$active $count $ip - [$country] WARNING: AbuseIPDB Score: $abuse_score%\e[0m"
elif [ "$abuse_score" -gt 0 ]; then
echo -e "\e[1;36m$active $count $ip - [$country] NOTICE: AbuseIPDB Score: $abuse_score%\e[0m"
else
echo "$active $count $ip - [$country] Clean: AbuseIPDB Score: $abuse_score%"
fi
else
if [ "$abuse_score" -gt 80 ]; then
echo "$active $count $ip - [$country] CRITICAL: AbuseIPDB Score: $abuse_score%"
elif [ "$abuse_score" -gt 50 ]; then
echo "$active $count $ip - [$country] WARNING: AbuseIPDB Score: $abuse_score%"
elif [ "$abuse_score" -gt 0 ]; then
echo "$active $count $ip - [$country] NOTICE: AbuseIPDB Score: $abuse_score%"
else
echo "$active $count $ip - [$country] Clean: AbuseIPDB Score: $abuse_score%"
fi
fi
done
# Show connections by local server port if enabled
if [ $SHOW_PORTS -eq 1 ]; then
echo ""
echo "CONNECTIONS BY SERVICE PORT:"
echo "-------------------"
# Get local ports for established connections
netstat -tn | grep ESTABLISHED | awk '{print $4}' | cut -d: -f2 | sort -n | uniq -c | sort -rn > "$CACHE_DIR/port_counts.txt"
# Display ports with service names
while read count port; do
service=$(get_service_name $port)
if [ ! -z "$service" ]; then
echo "$count $port ($service)"
else
echo "$count $port"
fi
done < <(head -$TOP_PORTS "$CACHE_DIR/port_counts.txt")
fi
# Count total connections
total=$(netstat -tn | grep ESTABLISHED | wc -l)
echo ""
echo "Total active connections: $total"
echo "Last updated: $(date)"
# Wait for refresh
sleep $REFRESH_RATE
done
User and ssh login audit
touch useraudit.sh && chmod +x useraudit.sh && nano useraudit.sh
./useraudit.sh && rm -f useraudit.sh
#!/bin/bash
echo "=========================================="
echo "SERVER: $(hostname)"
echo "DATE: $(date)"
echo "=========================================="
echo "=== Server User and SSH Activity Report ==="
echo
# Test if files exist
echo "--- File Existence Check ---"
echo "/etc/passwd exists: $([ -f /etc/passwd ] && echo "YES" || echo "NO")"
echo "/var/log/secure exists: $([ -f /var/log/secure ] && echo "YES" || echo "NO")"
echo "/var/log/auth.log exists: $([ -f /var/log/auth.log ] && echo "YES" || echo "NO")"
echo
echo "--- User Count Check ---"
echo "Total users in /etc/passwd: $(wc -l < /etc/passwd)"
echo "Users with UID >= 1000: $(awk -F: '$3 >= 1000' /etc/passwd | wc -l)"
echo "Users with bash shell: $(awk -F: '$7 ~ /bash/' /etc/passwd | wc -l)"
echo
echo "--- Users with SSH Login Activity ---"
if [ -f /var/log/secure ]; then
ssh_users=$(grep "Accepted password\|Accepted publickey" /var/log/secure | \
awk '{for(i=1; i<=NF; i++) if($i == "for") {print $(i+1); break}}' | \
sort | uniq)
if [ -n "$ssh_users" ]; then
echo "Users who have successfully logged in via SSH:"
echo "$ssh_users" | while read user; do
echo " $user"
done
else
echo "No successful SSH logins found in logs"
fi
elif [ -f /var/log/auth.log ]; then
ssh_users=$(grep "Accepted password\|Accepted publickey" /var/log/auth.log | \
awk '{for(i=1; i<=NF; i++) if($i == "for") {print $(i+1); break}}' | \
sort | uniq)
if [ -n "$ssh_users" ]; then
echo "Users who have successfully logged in via SSH:"
echo "$ssh_users" | while read user; do
echo " $user"
done
else
echo "No successful SSH logins found in logs"
fi
else
echo "No SSH log file found"
fi
echo
echo "--- All SSH Login Activities (All Available Logs) ---"
# Check all possible log locations including rotated logs
logfiles_found=0
# Check current and rotated secure logs
for logfile in /var/log/secure /var/log/secure-* /var/log/auth.log /var/log/auth.log-*; do
if [ -f "$logfile" ]; then
logfiles_found=1
echo "Checking $logfile..."
# Handle compressed files
if [[ "$logfile" == *.gz ]]; then
zcat "$logfile" 2>/dev/null | grep "Accepted password\|Accepted publickey" | \
awk '{
month = $1; day = $2;
for(i=1; i<=NF; i++) if($i == "for") {user=$(i+1); break}
for(i=1; i<=NF; i++) if($i == "from") {ip=$(i+1); break}
printf "%s %2s %s %s ssh2\n", month, day, user, ip;
}'
else
grep "Accepted password\|Accepted publickey" "$logfile" 2>/dev/null | \
awk '{
month = $1; day = $2;
for(i=1; i<=NF; i++) if($i == "for") {user=$(i+1); break}
for(i=1; i<=NF; i++) if($i == "from") {ip=$(i+1); break}
printf "%s %2s %s %s ssh2\n", month, day, user, ip;
}'
fi
echo
fi
done
if [ $logfiles_found -eq 0 ]; then
echo "No SSH log files found"
fi
echo "--- Historical SSH Login Summary ---"
# Combine all logs and show unique users with login counts
temp_file=$(mktemp)
for logfile in /var/log/secure /var/log/secure-* /var/log/auth.log /var/log/auth.log-*; do
if [ -f "$logfile" ]; then
if [[ "$logfile" == *.gz ]]; then
zcat "$logfile" 2>/dev/null | grep "Accepted password\|Accepted publickey"
else
grep "Accepted password\|Accepted publickey" "$logfile" 2>/dev/null
fi
fi
done > "$temp_file"
if [ -s "$temp_file" ]; then
echo "Login counts by user (all time):"
awk '{for(i=1; i<=NF; i++) if($i == "for") {print $(i+1); break}}' "$temp_file" | \
sort | uniq -c | sort -nr
else
echo "No SSH login activities found in any log files"
fi
rm -f "$temp_file"
echo
echo "--- All Users (Simple) ---"
awk -F: '{print $1}' /etc/passwd | sort
Access log analysis
touch access_analysis.sh && chmod +x access_analysis.sh && nano access_analysis.sh
./access_analysis.sh
#!/bin/bash
# Access Log Analysis Script
# Analyzes bot traffic, bandwidth usage, IP correlations, and access patterns
# Usage: ./analyze_logs.sh [http_log] [https_log]
# or: ./analyze_logs.sh /path/to/access.log
# or: ./analyze_logs.sh (uses default files in current directory)
# Configuration - Set your default log file paths here
DEFAULT_HTTP_LOG="hamiltonmontessorischool.com"
DEFAULT_HTTPS_LOG="hamiltonmontessorischool.com-ssl_log"
# Parse command line arguments
if [ $# -eq 0 ]; then
# No arguments - use defaults
HTTP_LOG="$DEFAULT_HTTP_LOG"
HTTPS_LOG="$DEFAULT_HTTPS_LOG"
echo "Using default log files: $HTTP_LOG and $HTTPS_LOG"
elif [ $# -eq 1 ]; then
# Single argument - analyze one log file only
HTTP_LOG="$1"
HTTPS_LOG=""
echo "Analyzing single log file: $HTTP_LOG"
elif [ $# -eq 2 ]; then
# Two arguments - HTTP and HTTPS logs
HTTP_LOG="$1"
HTTPS_LOG="$2"
echo "Analyzing HTTP log: $HTTP_LOG and HTTPS log: $HTTPS_LOG"
else
echo "Usage: $0 [http_log] [https_log]"
echo " or: $0 [single_log_file]"
echo " or: $0 (uses default files)"
exit 1
fi
# Verify files exist
if [ ! -f "$HTTP_LOG" ]; then
echo "Warning: HTTP log file '$HTTP_LOG' not found"
HTTP_LOG=""
fi
if [ -n "$HTTPS_LOG" ] && [ ! -f "$HTTPS_LOG" ]; then
echo "Warning: HTTPS log file '$HTTPS_LOG' not found"
HTTPS_LOG=""
fi
if [ -z "$HTTP_LOG" ] && [ -z "$HTTPS_LOG" ]; then
echo "Error: No valid log files found"
exit 1
fi
# Create combined log variable for analysis
ALL_LOGS=""
[ -n "$HTTP_LOG" ] && ALL_LOGS="$HTTP_LOG"
[ -n "$HTTPS_LOG" ] && ALL_LOGS="$ALL_LOGS $HTTPS_LOG"
echo "=== ACCESS LOG ANALYSIS REPORT ==="
echo "Generated: $(date)"
echo "Log files analyzed: $ALL_LOGS"
echo "======================================="
echo
echo "1. BASIC STATISTICS"
echo "==================="
[ -n "$HTTP_LOG" ] && echo "HTTP Log entries: $(wc -l < $HTTP_LOG 2>/dev/null)"
[ -n "$HTTPS_LOG" ] && echo "HTTPS Log entries: $(wc -l < $HTTPS_LOG 2>/dev/null)"
echo "Total requests: $(cat $ALL_LOGS 2>/dev/null | wc -l)"
echo
echo "2. BOT TRAFFIC ANALYSIS"
echo "======================="
echo "Bot identification by User-Agent:"
cat $ALL_LOGS 2>/dev/null | grep -i -E "(bot|crawler|spider)" | \
awk '{print $NF}' | sed 's/"//g' | sort | uniq -c | sort -nr
echo
echo "Known bots detected:"
echo "- PetalBot: $(cat $ALL_LOGS 2>/dev/null | grep -c "PetalBot")"
echo "- SemrushBot: $(cat $ALL_LOGS 2>/dev/null | grep -c "SemrushBot")"
echo "- BingBot: $(cat $ALL_LOGS 2>/dev/null | grep -c "bingbot")"
echo "- BingPreview: $(cat $ALL_LOGS 2>/dev/null | grep -c "BingPreview")"
echo
echo "3. IP ADDRESS CORRELATION"
echo "========================="
echo "Top 10 IP addresses by request count:"
cat $ALL_LOGS 2>/dev/null | awk '{print $1}' | sort | uniq -c | sort -nr | head -10
echo
echo "IP ranges analysis (Class C networks):"
cat $ALL_LOGS 2>/dev/null | awk '{print $1}' | cut -d. -f1-3 | sort | uniq -c | sort -nr | head -10
echo
echo "4. BANDWIDTH USAGE ANALYSIS"
echo "============================"
echo "Response sizes (bytes transferred):"
cat $ALL_LOGS 2>/dev/null | awk '{if($10 != "-") total+=$10; count++} END {print "Total bytes: " total "\nAverage response size: " (total/count) " bytes"}'
echo
echo "Largest responses:"
cat $ALL_LOGS 2>/dev/null | awk '{if($10 != "-" && $10 > 0) print $10, $7}' | sort -nr | head -10
echo
echo "5. HTTP STATUS CODE ANALYSIS"
echo "============================="
cat $ALL_LOGS 2>/dev/null | awk '{print $9}' | sort | uniq -c | sort -nr
echo
echo "6. MOST REQUESTED URLS"
echo "======================"
echo "Top 15 requested URLs:"
cat $ALL_LOGS 2>/dev/null | awk '{print $7}' | sort | uniq -c | sort -nr | head -15
echo
echo "7. SUSPICIOUS ACTIVITY PATTERNS"
echo "==============================="
echo "Dating/marriage related requests (potential spam):"
cat $ALL_LOGS 2>/dev/null | grep -i -E "(latin|ukrainian|german|ladies|marriage|dating|brides)" | wc -l
echo
echo "Sample suspicious URLs:"
cat $ALL_LOGS 2>/dev/null | grep -i -E "(latin|ukrainian|german|ladies|marriage|dating|brides)" | awk '{print $7}' | sort | uniq | head -5
echo
echo "8. TIME PATTERN ANALYSIS"
echo "========================"
echo "Requests by hour:"
cat $ALL_LOGS 2>/dev/null | awk '{gsub(/\[|\]/, "", $4); split($4, dt, ":"); print dt[2]}' | sort | uniq -c
echo
echo "9. REFERRER ANALYSIS"
echo "===================="
echo "Top referrers:"
cat $ALL_LOGS 2>/dev/null | awk -F'"' '{print $4}' | grep -v "^-$" | sort | uniq -c | sort -nr | head -10
echo
echo "10. USER AGENT ANALYSIS"
echo "======================="
echo "Top User Agents (non-bot):"
cat $ALL_LOGS 2>/dev/null | grep -v -i -E "(bot|crawler|spider)" | awk -F'"' '{print $6}' | sort | uniq -c | sort -nr | head -5
echo
echo "11. ERROR ANALYSIS"
echo "=================="
echo "4xx and 5xx errors:"
cat $ALL_LOGS 2>/dev/null | awk '{if($9 >= 400) print $9}' | sort | uniq -c | sort -nr
echo
echo "12. BANDWIDTH BY BOT TYPE"
echo "========================="
echo "Bandwidth usage by identified bots:"
echo "PetalBot total bytes: $(cat $ALL_LOGS 2>/dev/null | grep "PetalBot" | awk '{if($10 != "-") total+=$10} END {print total+0}')"
echo "SemrushBot total bytes: $(cat $ALL_LOGS 2>/dev/null | grep "SemrushBot" | awk '{if($10 != "-") total+=$10} END {print total+0}')"
echo "BingBot total bytes: $(cat $ALL_LOGS 2>/dev/null | grep "bingbot\|BingPreview" | awk '{if($10 != "-") total+=$10} END {print total+0}')"
echo
echo "13. GEOGRAPHIC IP ANALYSIS"
echo "=========================="
echo "IP ranges by region (estimated):"
echo "114.119.x.x (likely Asia/China): $(cat $ALL_LOGS 2>/dev/null | grep "^114\.119\." | wc -l) requests"
echo "185.191.x.x (likely Europe): $(cat $ALL_LOGS 2>/dev/null | grep "^185\.191\." | wc -l) requests"
echo "40.77.x.x (Microsoft/Bing): $(cat $ALL_LOGS 2>/dev/null | grep "^40\.77\." | wc -l) requests"
echo "15.204.x.x (likely AWS/Cloud): $(cat $ALL_LOGS 2>/dev/null | grep "^15\.204\." | wc -l) requests"
echo
echo "=== END OF ANALYSIS ==="
echo "Usage Examples:"
echo " $0 # Use default files"
echo " $0 access.log # Single log file"
echo " $0 http.log https.log # Two separate files"
echo " $0 /var/log/apache2/access.log # Full path"
echo " $0 /logs/site1.log /logs/site1-ssl.log # Different site"
echo ""
echo "To change default files, edit the variables at the top of this script:"
echo " DEFAULT_HTTP_LOG and DEFAULT_HTTPS_LOG"
# 1. Use default files (edit script to change defaults)
./analyze_logs.sh
# 2. Analyze a single log file
./analyze_logs.sh /var/log/apache2/access.log
./analyze_logs.sh access.log
# 3. Analyze two files (HTTP and HTTPS)
./analyze_logs.sh access.log ssl_access.log
./analyze_logs.sh /path/to/site1.log /path/to/site1-ssl.log
# 4. Different sites entirely
./analyze_logs.sh example.com.log example.com-ssl.log
Exim log file outgoing spam detection
touch exim_spam_scanner.sh && chmod +x exim_spam_scanner.sh && nano exim_spam_scanner.sh
./exim_spam_scanner.sh
#!/bin/bash
#
# Exim Spam Activity Scanner - Final Version
# Analyzes /var/log/exim_mainlog for evidence of ongoing spam sending
#
# Usage: ./exim_spam_scanner.sh [hours_to_analyze]
# Default: analyzes last 24 hours if no argument provided
#
# Colors for output
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'
# Configuration
LOGFILE="/var/log/exim_mainlog"
HOURS=${1:-24}
# Calculate the cutoff date
CUTOFF_DATE=$(date -d "$HOURS hours ago" '+%Y-%m-%d %H')
# Function to filter logs by date
filter_recent() {
awk -v cutoff="$CUTOFF_DATE" '$1 " " substr($2,1,2) >= cutoff' "$LOGFILE"
}
# Thresholds
THRESHOLD_MSGS_PER_ACCOUNT=100
THRESHOLD_MSGS_PER_SCRIPT=50
THRESHOLD_DUPLICATE_SUBJECT=50
THRESHOLD_IPS_PER_ACCOUNT=5
echo -e "${BLUE}================================================${NC}"
echo -e "${BLUE} Exim Spam Activity Analysis${NC}"
echo -e "${BLUE} Analyzing logs from last $HOURS hours${NC}"
echo -e "${BLUE}================================================${NC}\n"
if [ ! -f "$LOGFILE" ]; then
echo -e "${RED}ERROR: Log file $LOGFILE not found!${NC}"
exit 1
fi
echo -e "${YELLOW}[1] OUTBOUND email volume by authenticated accounts${NC}\n"
auth_accounts=$(filter_recent | grep "<=" | grep -E "A=dovecot_login:|A=dovecot_plain:" | \
awk -F'A=dovecot_' '{print $2}' | awk -F':' '{print $2}' | awk '{print $1}' | \
sort | uniq -c | sort -rn | head -20)
if [ -n "$auth_accounts" ]; then
echo "$auth_accounts" | while read count email; do
if [ -n "$count" ] && [ "$count" -gt "$THRESHOLD_MSGS_PER_ACCOUNT" ]; then
echo -e "${RED} ⚠ $count messages from: $email (SUSPICIOUS!)${NC}"
elif [ -n "$count" ]; then
echo -e "${GREEN} ✓ $count messages from: $email${NC}"
fi
done
else
echo -e "${GREEN} ✓ No authenticated sending detected${NC}"
fi
echo -e "\n${YELLOW}[2] Email sending by PHP/Web scripts${NC}\n"
scripts=$(filter_recent | grep "cwd=" | grep -v "cwd=/var/spool/exim" | \
grep -v "cwd=/etc/csf" | grep -v "cwd=/root" | \
awk -F'cwd=' '{print $2}' | awk '{print $1}' | \
sort | uniq -c | sort -rn | head -15)
if [ -n "$scripts" ]; then
echo "$scripts" | while read count path; do
if [ -n "$count" ] && [ "$count" -gt "$THRESHOLD_MSGS_PER_SCRIPT" ]; then
echo -e "${RED} ⚠ $count messages from: $path (SUSPICIOUS!)${NC}"
elif [ -n "$count" ]; then
echo -e "${GREEN} ✓ $count messages from: $path${NC}"
fi
done
else
echo -e "${GREEN} ✓ No script-based sending detected${NC}"
fi
echo -e "\n${YELLOW}[3] Duplicate email subjects (spam indicator)${NC}\n"
subjects=$(filter_recent | grep "<=" | grep 'T="' | \
grep -v 'T="Mail delivery failed' | \
awk -F'T="' '{print $2}' | awk -F'"' '{print $1}' | \
sort | uniq -c | sort -rn | head -15)
# Count bounce messages separately
bounce_count=$(filter_recent | grep "<=" | grep 'T="Mail delivery failed' | wc -l)
if [ "$bounce_count" -gt 0 ]; then
echo -e "${BLUE} ℹ $bounce_count bounce messages (delivery failures - normal when blacklisted)${NC}"
fi
if [ -n "$subjects" ]; then
echo "$subjects" | while read count subject; do
if [ -n "$count" ] && [ "$count" -gt "$THRESHOLD_DUPLICATE_SUBJECT" ]; then
echo -e "${RED} ⚠ $count messages: \"$subject\" (SUSPICIOUS!)${NC}"
elif [ -n "$count" ]; then
echo -e "${GREEN} ✓ $count messages: \"$subject\"${NC}"
fi
done
else
echo -e "${GREEN} ✓ No duplicate subjects found${NC}"
fi
echo -e "\n${YELLOW}[4] Accounts sending from multiple IPs${NC}\n"
multi_ip=$(filter_recent | grep "<=" | grep -E "A=dovecot_login:|A=dovecot_plain:" | \
awk -F'A=dovecot_' '{print $2}' | awk -F':' '{print $2}' | \
awk '{account=$1; for(i=2;i<=NF;i++){if($i ~ /H=/){split($i,a,"["); split(a[2],b,"]"); print account, b[1]; break}}}' | \
awk '{arr[$1]=arr[$1]","$2} END {for (i in arr) {split(arr[i],ips,","); delete seen; count=0; for(j in ips){if(ips[j] && !seen[ips[j]]++){count++}} if(count>1) print count, i, arr[i]}}' | \
sort -rn | head -10)
if [ -n "$multi_ip" ]; then
echo "$multi_ip" | while read count account ips; do
if [ -n "$count" ] && [ "$count" -gt "$THRESHOLD_IPS_PER_ACCOUNT" ]; then
echo -e "${RED} ⚠ $account from $count IPs: $(echo $ips | sed 's/,/ /g') (COMPROMISED?)${NC}"
elif [ -n "$count" ] && [ "$count" -gt 1 ]; then
echo -e "${YELLOW} ! $account from $count IPs: $(echo $ips | sed 's/,/ /g')${NC}"
fi
done
else
echo -e "${GREEN} ✓ No accounts sending from multiple IPs${NC}"
fi
echo -e "\n${YELLOW}[5] Blacklist impact analysis${NC}\n"
# Count different types of blacklist issues
legitimate_blocked=$(filter_recent | grep -E "\*\*" | \
grep -iE "spamhaus|blocked using" | \
grep -v "F=<bounces" | grep -v "F=<>" | wc -l)
bounce_blocked=$(filter_recent | grep -E "\*\*" | \
grep -iE "spamhaus|blocked using" | \
grep "F=<>" | wc -l)
if [ "$legitimate_blocked" -gt 0 ]; then
echo -e "${RED} ⚠ $legitimate_blocked legitimate outbound emails blocked by Spamhaus${NC}"
echo -e "${YELLOW} → Your business emails are being rejected due to IP reputation${NC}\n"
echo -e " Recent examples (showing last 3):"
filter_recent | grep -E "\*\*" | \
grep -iE "spamhaus|blocked using" | \
grep -v "F=<bounces" | grep -v "F=<>" | tail -3 | \
while IFS= read -r line; do
# Extract key info: timestamp, from, to
echo "$line" | awk '{
for(i=1;i<=NF;i++) {
if($i ~ /^F=</) from=$i
if($i ~ /\*\*/) to=$(i+1)
}
print " " $1 " " $2 " | From:" from " | To:" to
}'
done
else
echo -e "${GREEN} ✓ No legitimate outbound emails blocked${NC}"
fi
if [ "$bounce_blocked" -gt 0 ]; then
echo -e "\n${BLUE} ℹ $bounce_blocked bounce notifications also blocked (expected when blacklisted)${NC}"
fi
echo -e "\n${YELLOW}[6] High-volume sending patterns${NC}\n"
echo "Mail activity per hour (last $HOURS hours):"
echo "(OUT=authenticated/scripts, IN=from external servers, REJ=spam blocked)"
for i in $(seq $((HOURS-1)) -1 0); do
hour_ago=$(date -d "$i hours ago" '+%Y-%m-%d %H')
outbound=$(grep "^$hour_ago" "$LOGFILE" 2>/dev/null | grep "<=" | \
grep -E "A=dovecot_login:|A=dovecot_plain:|cwd=" | \
grep -v "cwd=/var/spool/exim" | grep -v "cwd=/etc/csf" | wc -l)
all_received=$(grep "^$hour_ago" "$LOGFILE" 2>/dev/null | grep "<=" | wc -l)
incoming=$((all_received - outbound))
rejected=$(grep "^$hour_ago" "$LOGFILE" 2>/dev/null | grep "rejected" | wc -l)
total=$((outbound + incoming + rejected))
bar=$(printf '█%.0s' $(seq 1 $((total/10))))
if [ "$outbound" -gt 100 ]; then
echo -e "${RED} $hour_ago:00 - OUT:$outbound IN:$incoming REJ:$rejected $bar (HIGH!)${NC}"
elif [ "$outbound" -gt 50 ]; then
echo -e "${YELLOW} $hour_ago:00 - OUT:$outbound IN:$incoming REJ:$rejected $bar${NC}"
elif [ "$incoming" -gt 100 ]; then
echo -e "${BLUE} $hour_ago:00 - OUT:$outbound IN:$incoming REJ:$rejected $bar${NC}"
else
echo -e "${GREEN} $hour_ago:00 - OUT:$outbound IN:$incoming REJ:$rejected $bar${NC}"
fi
done
echo -e "\n${YELLOW}[7] Suspicious sender patterns${NC}\n"
suspicious_count=$(filter_recent | grep "<=" | \
grep -E "F=<>|F=<no-reply@|F=<noreply@|F=<admin@|F=<info@|F=<support@" | wc -l)
if [ "$suspicious_count" -gt 50 ]; then
echo -e "${RED} ⚠ Found $suspicious_count messages with generic sender addresses${NC}"
else
echo -e "${GREEN} ✓ Only $suspicious_count messages with generic sender addresses${NC}"
fi
echo -e "\n${YELLOW}[8] Rapid-fire sending (bot behavior)${NC}\n"
rapid=$(filter_recent | grep "<=" | grep -E "A=dovecot_login:|A=dovecot_plain:" | \
awk '{
datetime=$1 " " substr($2,1,5) # Get YYYY-MM-DD HH:MM
line=$0
}
/A=dovecot_/ {
split($0, arr, "A=dovecot_")
split(arr[2], arr2, ":")
account=arr2[2]
gsub(/ .*/, "", account)
key=datetime ":" account
count[key]++
}
END {
for (k in count) {
if (count[k] > 20) { # More than 20 per minute is suspicious
split(k, b, ":")
print count[k], b[1] " " b[2], b[3]
}
}
}' | sort -rn | head -10)
if [ -n "$rapid" ]; then
echo "$rapid" | while read count datetime account; do
if [ -n "$count" ] && [ "$count" -gt 50 ]; then
echo -e "${RED} ⚠ $account: $count msgs/min at $datetime (SUSPICIOUS BOT!)${NC}"
elif [ -n "$count" ] && [ "$count" -gt 20 ]; then
echo -e "${YELLOW} ! $account: $count msgs/min at $datetime (high rate, investigate)${NC}"
fi
done
else
echo -e "${GREEN} ✓ No rapid-fire sending detected${NC}"
fi
echo -e "\n${YELLOW}[9] Blacklist status summary${NC}\n"
outbound_rejects=$(filter_recent | \
grep -iE "spamhaus|blocked using spamhaus" | \
grep -E "\*\*" | \
grep -v "F=<bounces" | grep -v "F=<>")
if [ -n "$outbound_rejects" ]; then
blacklist_count=$(echo "$outbound_rejects" | wc -l)
echo -e "${RED}⚠ $blacklist_count legitimate emails blocked by Spamhaus in last $HOURS hours${NC}"
echo -e "${YELLOW}→ This confirms your IP is currently blacklisted${NC}"
echo -e "${YELLOW}→ Your business emails are being rejected${NC}"
else
blacklist_count=0
echo -e "${GREEN}✓ No legitimate outbound mail blocked by blacklists${NC}"
echo -e "${GREEN}✓ Server appears clean - not currently sending spam${NC}"
fi
echo -e "\n${BLUE}================================================${NC}"
echo -e "${BLUE} Analysis Complete${NC}"
echo -e "${BLUE}================================================${NC}\n"
# Summary
truly_outbound=$(filter_recent | grep "<=" | \
grep -E "A=dovecot_login:|A=dovecot_plain:|cwd=" | \
grep -v "cwd=/var/spool/exim" | grep -v "cwd=/etc/csf" | wc -l)
all_received=$(filter_recent | grep "<=" | wc -l)
incoming=$((all_received - truly_outbound))
echo -e "${BLUE}╔════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ SPAM DETECTION VERDICT ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════╝${NC}\n"
# Determine if spam is being sent
spam_indicators=0
if [ "$truly_outbound" -gt 500 ]; then
((spam_indicators++))
fi
# Check for compromised accounts (from section 4)
multi_ip_count=$(filter_recent | grep "<=" | grep -E "A=dovecot_login:|A=dovecot_plain:" | \
awk -F'A=dovecot_' '{print $2}' | awk -F':' '{print $2}' | \
awk '{account=$1; for(i=2;i<=NF;i++){if($i ~ /H=/){split($i,a,"["); split(a[2],b,"]"); print account, b[1]; break}}}' | \
awk '{arr[$1]=arr[$1]","$2} END {for (i in arr) {split(arr[i],ips,","); delete seen; count=0; for(j in ips){if(ips[j] && !seen[ips[j]]++){count++}} if(count>5) print i}}' | wc -l)
if [ "$multi_ip_count" -gt 0 ]; then
((spam_indicators++))
fi
# Check for duplicate subjects (excluding bounces)
spam_subjects=$(filter_recent | grep "<=" | grep 'T="' | grep -v 'T="Mail delivery failed' | \
awk -F'T="' '{print $2}' | awk -F'"' '{print $1}' | \
sort | uniq -c | awk '$1 > 100' | wc -l)
if [ "$spam_subjects" -gt 0 ]; then
((spam_indicators++))
fi
if [ "$spam_indicators" -eq 0 ]; then
echo -e "${GREEN}✓✓✓ NO SPAM ACTIVITY DETECTED ✓✓✓${NC}"
echo -e "${GREEN}Server is CLEAN - not sending spam${NC}\n"
else
echo -e "${RED}⚠⚠⚠ SPAM ACTIVITY DETECTED ⚠⚠⚠${NC}"
echo -e "${RED}Found $spam_indicators spam indicators${NC}\n"
fi
echo -e "\n${YELLOW}SUMMARY:${NC}"
echo -e " Outbound (authenticated/scripts): ${BLUE}$truly_outbound${NC}"
echo -e " Incoming (from other servers): ${BLUE}$incoming${NC}"
echo -e " Total: ${BLUE}$all_received${NC}\n"
if [ "$spam_indicators" -eq 0 ]; then
if [ "$truly_outbound" -lt 10 ]; then
echo -e "${GREEN}✓ Very low outbound volume - no spam activity${NC}"
elif [ "$truly_outbound" -lt 200 ]; then
echo -e "${GREEN}✓ Normal outbound volume - legitimate business email${NC}"
else
echo -e "${GREEN}✓ Moderate outbound volume - appears legitimate${NC}"
fi
fi
if [ "$blacklist_count" -eq 0 ]; then
echo -e "${GREEN}✓ No current blacklist rejections of legitimate mail${NC}"
echo -e "${YELLOW}→ Any blacklisting is from PAST activity${NC}"
echo -e "${YELLOW}→ Focus on delisting requests, not finding spam sources${NC}"
else
echo -e "${RED}⚠ Active blacklist impact: $blacklist_count legitimate emails rejected${NC}"
echo -e "${YELLOW}→ Your business emails cannot reach recipients${NC}"
echo -e "${YELLOW}→ Priority: Get delisted from Spamhaus immediately${NC}"
echo -e "${YELLOW}→ Visit: https://www.spamhaus.org/query/ip/67.225.154.71${NC}"
fi
echo ""