simple-admin/simpleadmin/www/cgi-bin/get_system_stats
2024-12-08 19:08:25 +08:00

41 lines
1.3 KiB
Bash

#!/bin/sh
# Send HTTP header for plain text content
echo "Content-Type: text/plain"
echo ""
# Read first CPU statistics
read cpu user nice system idle iowait irq softirq steal guest guest_nice < /proc/stat
# Record first total usage time and idle time
prev_total=$((user+nice+system+idle+iowait+irq+softirq+steal))
prev_idle=$idle
# Wait for a short time to capture CPU usage
sleep 0.5
# Read second CPU statistics
read cpu user nice system idle iowait irq softirq steal guest guest_nice < /proc/stat
# Calculate second total usage time
total=$((user+nice+system+idle+iowait+irq+softirq+steal))
idle=$idle
# Calculate time differences
total_diff=$((total-prev_total))
idle_diff=$((idle-prev_idle))
# Calculate CPU usage percentage
cpu_usage=$(awk -v total_diff="$total_diff" -v idle_diff="$idle_diff" 'BEGIN{printf "%.1f", (total_diff-idle_diff)*100/total_diff}')
# Get memory information
mem_info=$(free -m | grep "Mem:")
mem_total=$(echo "$mem_info" | awk '{print $2}')
mem_used=$(echo "$mem_info" | awk '{print $3}')
mem_usage=$(awk "BEGIN {printf \"%.1f\", ($mem_used * 100) / $mem_total}")
# Output results
echo "CPU Usage: $cpu_usage"
echo "Memory Usage: $mem_usage"
echo "Memory Total: $((mem_total * 1024 * 1024))"
echo "Memory Used: $((mem_used * 1024 * 1024))"