Skip to content

Instantly share code, notes, and snippets.

@Staubgeborener
Forked from funvill/gist:5252169
Last active October 30, 2018 04:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Staubgeborener/6aeb38239d7f00624738e02047b59109 to your computer and use it in GitHub Desktop.
Save Staubgeborener/6aeb38239d7f00624738e02047b59109 to your computer and use it in GitHub Desktop.
Get the system stats on the raspberry pi or any linux system in python
#This Script needs Python3. Original script from @funvill,
#edit (urllib and http/request support, also added gpu temperature) by @staubgeborener
#This edit allows to post raspberry pi stats on any php supported website. You could use this together with cron for example.
import os
import urllib.request, urllib.parse
# Return CPU temperature as a character string
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
return(res.replace("temp=","").replace("'C\n",""))
def getGPUtemperature():
ret = os.popen('vcgencmd measure_temp').readline();
temperature = ret.replace("temp=","").replace("'C\n","");
return(float(temperature))
# Return RAM information (unit=kb) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
p = os.popen('free')
i = 0
while 1:
i = i + 1
line = p.readline()
if i==2:
return(line.split()[1:4])
# Return % of CPU used by user as a character string
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
# Return information about disk space as a list (unit included)
# Index 0: total disk space
# Index 1: used disk space
# Index 2: remaining disk space
# Index 3: percentage of disk used
def getDiskSpace():
p = os.popen("df -h /")
i = 0
while 1:
i = i +1
line = p.readline()
if i==2:
return(line.split()[1:5])
disk_call = getDiskSpace()
ram_call = getRAMinfo()
data = {
'cpu' : getCPUtemperature(),
'gpu' : getGPUtemperature(),
'cpuuse' : getCPUuse(),
'ram_total' : ram_call[0],
'ram_used' : ram_call[1],
'ram_free' : ram_call[2],
'disk_total' : disk_call[0],
'disk_used' : disk_call[1],
'disk_free' : disk_call[2],
'disk_percent' : disk_call[3]
}
data = bytes( urllib.parse.urlencode( data ).encode() )
handler = urllib.request.urlopen( 'http://example-site.de/data_collector.php', data );
print( handler.read().decode( 'utf-8' ) );
@Staubgeborener
Copy link
Author

Staubgeborener commented Dec 1, 2017

Example for php code:

<?php
if( $_REQUEST["cpu"] ) {  //if-statement not necessary
	$var1 = $_REQUEST['cpu'];
	$var2 = $_REQUEST['gpu'];
	$var3 = $_REQUEST['cpuuse'];
	$var4 = $_REQUEST['ram_total'];
	$var5 = $_REQUEST['ram_used'];
	$var6 = $_REQUEST['ram_free'];
	$var7 = $_REQUEST['disk_total'];
	$var8 = $_REQUEST['disk_used'];
	$var9 = $_REQUEST['disk_free'];
	$var10 = $_REQUEST['disk_percent'];
}
?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment