Guest User

AVG CPU/RAM

a guest
Jan 6th, 2024
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.90 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Log file location
  4. LOG_FILE="<pathToLogfile>/cpu_ram_usage.log"
  5.  
  6. # MQTT Broker details
  7. MQTT_HOST=<yourMQTTBroker>
  8. MQTT_PORT=<yourMQTTPort (default 1883)>
  9. MQTT_TOPIC=<yourBaseTopicForMonitoredVM> # NOTE: on the "pub" below Iยดve attached CPU / RAM to the base topic in order to distinguish between them
  10. MQTT_USER=<yourMQTTUser>
  11. MQTT_PASS=<yourMQTTUserPass>
  12.  
  13. exec > "$LOG_FILE" 2>&1
  14. while true; do
  15.     # Initialize total CPU and RAM usage
  16.     total_cpu=0
  17.     total_ram=0
  18.     count=0
  19.  
  20.     # Function to get CPU and RAM usage
  21.     get_usage() {
  22.         # Get CPU usage as percentage
  23.         cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
  24.  
  25.         # Get RAM usage as percentage
  26.         ram_total=$(grep MemTotal /proc/meminfo | awk '{print $2 / 1024}') # in MiB
  27.         ram_available=$(grep MemAvailable /proc/meminfo | awk '{print $2 / 1024}') # in MiB
  28.         ram_usage=$(echo "scale=2; 100 - ($ram_available / $ram_total * 100)" | bc)
  29.  
  30.         # Accumulate total CPU and RAM usage
  31.         total_cpu=$(echo "$total_cpu + $cpu_usage" | bc)
  32.         total_ram=$(echo "$total_ram + $ram_usage" | bc)
  33.         count=$((count + 1))
  34.     }
  35.  
  36.     # Collect data every minute for 1 hour
  37.     for i in {1..60}; do
  38.         get_usage
  39.         sleep 60
  40.     done
  41.  
  42.     # Calculate average CPU and RAM usage
  43.     avg_cpu=$(echo "$total_cpu / $count" | bc -l)
  44.     avg_ram=$(echo "$total_ram / $count" | bc -l)
  45.  
  46.     # Format to 2 decimal places
  47.     formatted_avg_cpu=$(printf "%.2f" $avg_cpu)
  48.     formatted_avg_ram=$(printf "%.2f" $avg_ram)
  49.  
  50.  
  51.     # Publish the average to MQTT topic
  52.     mosquitto_pub -h "$MQTT_HOST" -p $MQTT_PORT -u $MQTT_USER -P $MQTT_PASS -t "$MQTT_TOPIC/cpu" -m "$formatted_avg_cpu"
  53.     mosquitto_pub -h "$MQTT_HOST" -p $MQTT_PORT -u $MQTT_USER -P $MQTT_PASS -t "$MQTT_TOPIC/ram" -m "$formatted_avg_ram"
  54.  
  55.     echo "Published average CPU and RAM usage to MQTT topic."
  56. done
Add Comment
Please, Sign In to add comment