Linux - Stats over MQTT

From The TinkerNet Wiki
Jump to navigation Jump to search

/usr/local/bin/MQTTstats.sh

 1 # Get uptime
 2 if [ -f "/proc/uptime" ]; then
 3 uptime=`cat /proc/uptime`
 4 uptime=${uptime%%.*}
 5 seconds=$(( uptime%60 ))
 6 minutes=$(( uptime/60%60 ))
 7 hours=$(( uptime/60/60%24 ))
 8 days=$(( uptime/60/60/24 ))
 9 fi
10 
11 # Get loadavg
12 if [ -f "/proc/loadavg" ]; then
13 OneMin=`cat /proc/loadavg | cut -b 1-4`
14 FiveMin=`cat /proc/loadavg | cut -b 6-9`
15 FifteenMin=`cat /proc/loadavg | cut -b 11-14`
16 fi
17 
18 # Get % Memory usage
19 MemUsed=`/usr/bin/free -t | grep "Mem:" | awk '{print (1-($7/$2))*100}'`
20 
21 printf '{\t"uptime":"%s:%s:%s:%s",\n' "$days" "$hours" "$minutes" "$seconds"
22 printf '\t"loadavg1min":%.2f,\n' "$OneMin"
23 printf '\t"loadavg5min":%.2f,\n' "$FiveMin"
24 printf '\t"loadavg15min":%.2f,\n' "$FifteenMin"
25 printf '\t"loadavg":"%s %s %s",\n' "$OneMin" "$FiveMin" "$FifteenMin"
26 printf '\t"memused":%.2f,\n' "$MemUsed"
27 printf '"SENSORS":'
28 printf '%s' `/usr/bin/sensors -j`
29 printf '}\n'

Don't forget to make it executable...

  • sudo chmod +x /usr/local/bin/MQTTstats.sh

(Yes... If you haven't yet installed the Mosquitto Clients, it's not gonna work... :P )

The cron job

Add this line by editing roots crontab

  • sudo crontab -e

& add this line at the end:

  • * * * * * /usr/bin/mosquitto_pub -h broker.domain.tld -t `hostname` -m "`/usr/local/bin/MQTTstats.sh`"

replace broker.domain.tld with the address of your broker