``` #!/bin/bash
cpu_usage_threshold=80 cpu_duration_threshold=60 memory_usage_threshold=70 memory_duration_threshold=70 disk_usage_threshold=90 disk_duration_threshold=90 interval=5 server_ip=$(ip addr show | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | cut -d/ -f1)
while true; do current_time=$(date +%s)
# CPU Usage
cpu_usage=$(top -b -n 1 | awk '/Cpu/ {print $2}' | cut -d. -f1)
if [ $cpu_usage -gt $cpu_usage_threshold ]; then
cpu_start_time=${cpu_start_time:-$current_time}
if [ $((current_time-cpu_start_time)) -gt $cpu_duration_threshold ]; then
top_cpu_processes=$(ps -eo pid,%cpu,comm --sort=-%cpu | head -n 4 | awk '{print $3}')
data=$(printf '{"server_ip":"%s","current_usage":%d,"duration":%d,"top_processes":["%s"]}' "$server_ip" "$cpu_usage" "$((current_time-cpu_start_time))" "$top_cpu_processes")
curl -H "Content-Type: application/json" -X POST -d "$data" http://aaa.com
unset cpu_start_time
fi
else
unset cpu_start_time
fi
# Memory Usage
memory_usage=$(free | awk '/Mem/ {printf("%.0f"), $3/$2*100}')
if [ ${memory_usage%.*} -gt $memory_usage_threshold ]; then
memory_start_time=${memory_start_time:-$current_time}
if [ $((current_time-memory_start_time)) -gt $memory_duration_threshold ]; then
top_memory_processes=$(ps -eo pid,%mem,comm --sort=-%mem | head -n 4 | awk '{print $3}')
data=$(printf '{"server_ip":"%s","current_usage":%d,"duration":%d,"top_processes":["%s"]}' "$server_ip" "$memory_usage" "$((current_time-memory_start_time))" "$top_memory_processes")
curl -H "Content-Type: application/json" -X POST -d "$data" http://aaa.com
unset memory_start_time
fi
else
unset memory_start_time
fi
# Disk Usage
disk_usage=$(df -h | awk '$NF=="/"{printf("%.0f"), $5}')
if [ ${disk_usage%.*} -gt $disk_usage_threshold ]; then
disk_start_time=${disk_start_time:-$current_time}
if [ $((current_time-disk_start_time)) -gt $disk_duration_threshold