Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Log file location
- LOG_FILE="<pathToLogfile>/cpu_ram_usage.log"
- # MQTT Broker details
- MQTT_HOST=<yourMQTTBroker>
- MQTT_PORT=<yourMQTTPort (default 1883)>
- MQTT_TOPIC=<yourBaseTopicForMonitoredVM> # NOTE: on the "pub" below Iยดve attached CPU / RAM to the base topic in order to distinguish between them
- MQTT_USER=<yourMQTTUser>
- MQTT_PASS=<yourMQTTUserPass>
- exec > "$LOG_FILE" 2>&1
- while true; do
- # Initialize total CPU and RAM usage
- total_cpu=0
- total_ram=0
- count=0
- # Function to get CPU and RAM usage
- get_usage() {
- # Get CPU usage as percentage
- cpu_usage=$(top -bn1 | grep "Cpu(s)" | awk '{print $2 + $4}')
- # Get RAM usage as percentage
- ram_total=$(grep MemTotal /proc/meminfo | awk '{print $2 / 1024}') # in MiB
- ram_available=$(grep MemAvailable /proc/meminfo | awk '{print $2 / 1024}') # in MiB
- ram_usage=$(echo "scale=2; 100 - ($ram_available / $ram_total * 100)" | bc)
- # Accumulate total CPU and RAM usage
- total_cpu=$(echo "$total_cpu + $cpu_usage" | bc)
- total_ram=$(echo "$total_ram + $ram_usage" | bc)
- count=$((count + 1))
- }
- # Collect data every minute for 1 hour
- for i in {1..60}; do
- get_usage
- sleep 60
- done
- # Calculate average CPU and RAM usage
- avg_cpu=$(echo "$total_cpu / $count" | bc -l)
- avg_ram=$(echo "$total_ram / $count" | bc -l)
- # Format to 2 decimal places
- formatted_avg_cpu=$(printf "%.2f" $avg_cpu)
- formatted_avg_ram=$(printf "%.2f" $avg_ram)
- # Publish the average to MQTT topic
- mosquitto_pub -h "$MQTT_HOST" -p $MQTT_PORT -u $MQTT_USER -P $MQTT_PASS -t "$MQTT_TOPIC/cpu" -m "$formatted_avg_cpu"
- mosquitto_pub -h "$MQTT_HOST" -p $MQTT_PORT -u $MQTT_USER -P $MQTT_PASS -t "$MQTT_TOPIC/ram" -m "$formatted_avg_ram"
- echo "Published average CPU and RAM usage to MQTT topic."
- done
Add Comment
Please, Sign In to add comment