Difference between revisions of "Linux - Stats over MQTT"

From Da Nerd Mage Wiki
Jump to navigation Jump to search
(Created page with "=== /usr/local/bin/MQTTstats.sh === <syntaxhighlight lang="sh" line="1"> # Get uptime if [ -f "/proc/uptime" ]; then uptime=`cat /proc/uptime` uptime=${uptime%%.*} seconds=$(( uptime%60 )) minutes=$(( uptime/60%60 )) hours=$(( uptime/60/60%24 )) days=$(( uptime/60/60/24 )) fi # Get loadavg if [ -f "/proc/loadavg" ]; then OneMin=`cat /proc/loadavg {{!}} cut -b 1-4` FiveMin=`cat /proc/loadavg {{!}} cut -b 6-9` FifteenMin=`cat /proc/loadavg {{!}} cut -b 11-14` fi # Get %...")
 
Line 1: Line 1:
== Requirements: ==
* <code>apt install mosquitto-clients</code>
* <code>apt install lm-sensors</code>
=== /usr/local/bin/MQTTstats.sh ===
=== /usr/local/bin/MQTTstats.sh ===
<syntaxhighlight lang="sh" line="1">
<syntaxhighlight lang="sh" line="1">

Revision as of 17:07, 14 April 2023

Requirements:

  • apt install mosquitto-clients
  • apt install lm-sensors

/usr/local/bin/MQTTstats.sh

# Get uptime
if [ -f "/proc/uptime" ]; then
uptime=`cat /proc/uptime`
uptime=${uptime%%.*}
seconds=$(( uptime%60 ))
minutes=$(( uptime/60%60 ))
hours=$(( uptime/60/60%24 ))
days=$(( uptime/60/60/24 ))
fi

# Get loadavg
if [ -f "/proc/loadavg" ]; then
OneMin=`cat /proc/loadavg {{!}} cut -b 1-4`
FiveMin=`cat /proc/loadavg {{!}} cut -b 6-9`
FifteenMin=`cat /proc/loadavg {{!}} cut -b 11-14`
fi

# Get % Memory usage
MemUsed=`/usr/bin/free -t {{!}} grep "Mem:" {{!}} awk '{print (1-($7/$2))*100}'`

printf '{\t"uptime":"%s:%s:%s:%s",\n' "$days" "$hours" "$minutes" "$seconds"
printf '\t"loadavg1min":%.2f,\n' "$OneMin"
printf '\t"loadavg5min":%.2f,\n' "$FiveMin"
printf '\t"loadavg15min":%.2f,\n' "$FifteenMin"
printf '\t"loadavg":"%s %s %s",\n' "$OneMin" "$FiveMin" "$FifteenMin"
printf '\t"memused":%.2f,\n' "$MemUsed"
printf '"SENSORS":'
printf '%s' `/usr/bin/sensors -j`
printf '}\n'

Don't forget to make it executable...

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

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

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