``` #!/bin/bash
cpu_threshold=80 cpu_duration=60 mem_threshold=70 mem_duration=70 disk_threshold=90 disk_duration=90 interval=60 url="http://aaa.com"
while true; do ip=$(hostname -I)
CPU usage
cpu_usage=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, ([0-9.])% id./\1/" | awk '{printf "%.1f\n", 100 - $1}') if (( $(echo "$cpu_usage > $cpu_threshold" | bc -l) )); then cpu_time=$((cpu_time + interval)) if (( $cpu_time > $cpu_duration )); then cpu_time=0 top_procs=$(ps -eo pid,user,%cpu,cmd --sort=-%cpu | head -n 4) data="{"server_ip":"$ip","resource_type":"cpu","usage":"$cpu_usage","duration":"$cpu_duration","top_procs":"$top_procs"}" curl -H "Content-Type: application/json" -X POST -d "$data" "$url" fi else cpu_time=0 fi
Memory usage
mem_usage=$(free | awk '/Mem/ {printf "%.1f\n", $3/$2 * 100.0}') if (( $(echo "$mem_usage > $mem_threshold" | bc -l) )); then mem_time=$((mem_time + interval)) if (( $mem_time > $mem_duration )); then mem_time=0 top_procs=$(ps -eo pid,user,%mem,cmd --sort=-%mem | head -n 4) data="{"server_ip":"$ip","resource_type":"memory","usage":"$mem_usage","duration":"$mem_duration","top_procs":"$top_procs"}" curl -H "Content-Type: application/json" -X POST -d "$data" "$url" fi else mem_time=0 fi
Disk usage
disk_usage=$(df -h | awk '$NF=="/"{printf "%s\n", $5}') disk_usage=${disk_usage%?} if (( $(echo "$disk_usage > $disk_threshold" | bc -l) )); then disk_time=$((disk_time + interval)) if (( $disk_time > $disk_duration )); then disk_time=0 top_files=$(du -ah / | sort -nr | head -n 3) data="{"server_ip":"$ip","resource_type":"disk","usage":"$disk_usage","duration":"$disk_duration","top_files":"$top_files"}" curl -H "Content-Type: application/json" -X POST -d "$data" "$url" fi else disk_