Python System Status Script

Aus Laub-Home Wiki

Möchte man via Python den Status einen Systems (zum Beispiel die System Load und die Ram Auslastung) auslesen kann man dies mit den Python Libraries gpiozero und psutil machen. Hat man die Werte erst einmal ausgelesen kann man diese auch noch direkt über einen MQTT Broker dem SmartHome zukommen lassen, um sie dort weiter zu verarbeiten, zum Beispiel mit openHAB und Grafana. Für das publizieren via MQTT verwenden wir dann die Python Library paho-mqtt. Als MQTT Convention kommt dann noch die Homie Convention zum Einsatz, was das Einbinden in unser SmartHome Hub deutlich vereinfacht.

Das Script liest die Uptime des Systems, die CPU-Temperatur und -Auslastung, die System Load, den Ram und die Festplatte (/) aus.

Der Output des systemstats.py Scripts ist folgender:

---System Informations---
System Uptime: 19:40:41.538989 - 1181 min
CPU Temperatur: 37.4 °C
CPU Usage: 1 %
Load average: 0.23 0.25 0.16
Ram Total: 368.4 MiB
Ram Used: 35.7 MiB
Ram Free: 137.0 MiB
Ram Usage: 28.3 %
Disk Total: 29.0 GiB
Disk Used: 2.1 GiB
Disk Free: 25.7 GiB
Disk Usage: 7.4 %

Via MQTT und Homie MQTT werden die folgenden Topics, bzw. Properties publiziert:

uptime uptime_min cpu_temp cpu_usage load_1 load_5 load_15 ram_total ram_used ram_free ram_percent_used disk_total disk_used disk_free disk_percent_used

Voraussetzungen

zuerst muss natürlich Python3 und die benötigten Libraries installiert werden:

apt update && apt install python3 python3-pip python3-paho-mqtt python3-gpiozero python3-psutil python3-systemd

# oder via pip3
pip3 install paho-mqtt
pip3 install psutil
pip3 install gpiozero
pip3 install systemd

Möchte man einen MQTT Broker verwenden und noch keinen haben, schaut hier rein:

System Status Script mit Ausgabe

Download hier möglich:

systemstats.py

#!/usr/bin/python3
from gpiozero import CPUTemperature
import psutil
import datetime

# do the stuff
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())
uptime_min = (uptime.seconds+uptime.days*24*3600)/60

cpu_temp = CPUTemperature()

cpu_usage = psutil.cpu_percent(interval=1, percpu=False)

load_1, load_5, load_15 = psutil.getloadavg()

ram = psutil.virtual_memory()
ram_total = ram.total / 2**20       # MiB.
ram_used = ram.used / 2**20
ram_free = ram.free / 2**20
ram_percent_used = ram.percent

disk = psutil.disk_usage('/')
disk_total = disk.total / 2**30     # GiB.
disk_used = disk.used / 2**30
disk_free = disk.free / 2**30
disk_percent_used = disk.percent

print("---System Informations---")
print("System Uptime: %s - %.0f min" % (uptime, uptime_min))
print("CPU Temperatur: {:.1f}".format(cpu_temp.temperature) + " °C")
print("CPU Usage: {:.0f} %".format(cpu_usage))
print("Load average: %.2f %.2f %.2f" % (load_1, load_5, load_15))
print("Ram Total: %.1f MiB\nRam Used: %.1f MiB\nRam Free: %.1f MiB\nRam Usage: %.1f %%" % (ram_total, ram_used, ram_free, ram_percent_used))
print("Disk Total: %.1f GiB\nDisk Used: %.1f GiB\nDisk Free: %.1f GiB\nDisk Usage: %.1f %%" % (disk_total, disk_used, disk_free, disk_percent_used))

so kann man das Script einfach herunterladen und starten.

cd /usr/local/sbin
wget https://github.com/alaub81/python_systemstats/raw/main/systemstats.py
chmod +x systemstats.py 
systemstats.py

System Status Script mit MQTT Einbindung

Download hier möglich:

systemstats-mqtt.py

#!/usr/bin/python3
from gpiozero import CPUTemperature
import psutil
import datetime
import paho.mqtt.client as mqtt
import ssl

# set the variables
broker = "FQDN / IP ADDRESS"
port = 8883
publish_topic = "home/DEVICENAME"
clientid = "DEVICENAME-systemstats"
username = "mosquitto"
password = "PASSWORD"
insecure = True
qos = 1
retain_message = True


# do the stuff
uptime = datetime.datetime.now() - datetime.datetime.fromtimestamp(psutil.boot_time())
uptime_min = (uptime.seconds+uptime.days*24*3600)/60

cpu_temp = CPUTemperature()

cpu_usage = psutil.cpu_percent(interval=1, percpu=False)

load_1, load_5, load_15 = psutil.getloadavg()

ram = psutil.virtual_memory()
ram_total = ram.total / 2**20       # MiB.
ram_used = ram.used / 2**20
ram_free = ram.free / 2**20
ram_percent_used = ram.percent

disk = psutil.disk_usage('/')
disk_total = disk.total / 2**30     # GiB.
disk_used = disk.used / 2**30
disk_free = disk.free / 2**30
disk_percent_used = disk.percent

def publish(topic, payload):
  client.publish(publish_topic + "/" + topic,payload,qos,retain_message)

#MQTT Connection
client=mqtt.Client(clientid)
client.username_pw_set(username, password)
client.tls_set(cert_reqs=ssl.CERT_NONE) #no client certificate needed
client.tls_insecure_set(insecure)
client.connect(broker, port)
client.loop_start()

#Publish the stuff
publish("uptime", str(uptime))
publish("uptime_min", (uptime_min))
publish("cpu_temp", cpu_temp.temperature)
publish("cpu_usage", cpu_usage)
publish("load_1", load_1)
publish("load_5", load_5)
publish("load_15", load_15)
publish("ram_total", ram_total)
publish("ram_used", ram_used)
publish("ram_free", ram_free)
publish("ram_percent_used", ram_percent_used)
publish("disk_total", disk_total)
publish("disk_used", disk_used)
publish("disk_free", disk_free)
publish("disk_percent_used", disk_percent_used)

#MQTT Disconnect
client.disconnect()
client.loop_stop()


"""
print("---System Informations---")
print("System Uptime: %s - %.0f min" % (uptime, uptime_min))
print("CPU Temperatur: {:.1f}".format(cpu_temp.temperature) + " °C")
print("CPU Usage: {:.0f} %".format(cpu_usage))
print("Load average: %.2f %.2f %.2f" % (load_1, load_5, load_15))
print("Ram Total: %.1f MiB\nRam Used: %.1f MiB\nRam Free: %.1f MiB\nRam Usage: %.1f %%" % (ram_total, ram_used, ram_free, ram_percent_used))
print("Disk Total: %.1f GiB\nDisk Used: %.1f GiB\nDisk Free: %.1f GiB\nDisk Usage: %.1f %%" % (disk_total, disk_used, disk_free, disk_percent_used))
"""

So kann man das Script herunterladen und konfigurieren. Ihr müsst die Daten für euren MQTT Broker hinterlegen.

cd /usr/local/sbin
wget https://github.com/alaub81/python_systemstats/raw/main/systemstats-mqtt.py
chmod +x systemstats-mqtt.py
nano systemstats-mqtt.py

gestartet wird das Script dann einfach so:

systemstats-mqtt.py

Möchte man das Script regelmäßig starten lassen, zum Beispiel alle Minute, dann legt einfach dafür einen cronjob an.

System Status Script - Homie MQTT und Systemd Service

Das Script publiziert seine Daten im Homie Convention MQTT Standard und kann so sehr einfach in den gängigen SmartHome Systemen eingebunden werden. Das Script wird von einem Systemd Service gestartet und läuft so im Hintergrund. Die Installation läuft wie folgt:

cd /usr/local/sbin
wget https://github.com/alaub81/python_systemstats/raw/main/systemstats-homie.py
chmod +x systemstats-homie.py 
nano systemstats-homie.py

Dann konfigurieren wir im oberen Teil den MQTT Broker und ggf, die Zeit, wie oft gemessen und publiziert werden soll.

# set the variables
broker = "FQDN / IP ADDRESS"
port = 8883
mqttclientid = "clientid-systemstats-homie"
clientid = "clientid-systemstats"
clientname = "Clientname System Statistics"
nodes="systemstats"
username = "mosquitto"
password = "password"
insecure = True
qos = 1
retain_message = True
# Retry to connect to mqtt broker
mqttretry = 5
# how often should be a publish to MQTT (in Seconds)
publishtime = 30
# Show System Stat output
showinfo =F alse

Dann installieren wir den Systemd Service und starten alles.

cd /etc/systemd/system
wget https://github.com/alaub81/python_systemstats/raw/main/systemstats-homie.service
systemctl daemon-reload
systemctl enable systemstats-homie.service
systemctl start systemstats-homie.service

Nun überprüfen wir ob alles läuft...

systemctl status systemstats-homie.service

Ausgabe sollte in etwa so aussehen.

● systemstats-homie.service - Python Systemstats MQTT Homie Service
     Loaded: loaded (/etc/systemd/system/systemstats-homie.service; enabled; vendor preset: enabled)
     Active: active (running) since Sun 2021-11-14 13:19:35 CET; 1min 5s ago
   Main PID: 5555 (python3)
      Tasks: 2 (limit: 415)
        CPU: 2.859s
     CGroup: /system.slice/systemstats-homie.service
             └─5555 /usr/bin/python3 /usr/local/sbin/systemstats-homie.py

Im MQTT Explorer solltet ihr dann auch die Messages sehen:

openHAB Einbindung

Wenn ihr nun die Daten in openHAB verwenden möchtet, dann schaut hier mal rein:

GitHub Repository

alle Scripte und Dateien, findet ihr in folgendem GitHub Repository: