Skip to content

Instantly share code, notes, and snippets.

@fahadysf
Last active April 25, 2020 01:43
Show Gist options
  • Save fahadysf/5b93d665d78a0407696ee041c683f629 to your computer and use it in GitHub Desktop.
Save fahadysf/5b93d665d78a0407696ee041c683f629 to your computer and use it in GitHub Desktop.
Python 2 script to extract 'sensors' command temperature readings
#!/usr/bin/env python
"""
Script to create output of Physical Package CPU Temperature
using the sensors command. Handy for feeding to NetXMS with the below
Agent Config line
ExternalParameterShellExec=CPUTemperature(*): python /root/check-temp.py $1
"""
import sys
import subprocess
def run_process(command):
command_components = command.split(" ")
output = subprocess.check_output(command_components)
return output
def parse_sensors_output(data):
"""
This function takes the sensors output and breaks it intosensor-name,
Adapter/Value and ID/Value tuples
"""
outputdict = dict()
datalines = data.splitlines()
for line in datalines:
if ':' not in line and line.strip() != "":
sensor = line.strip()
outputdict[sensor] = dict()
elif ':' in line:
if "Adapter:" in line:
outputdict[sensor]["Adapter"] = (line.split(':')[-1]).strip()
elif ":" in line:
splitline = line.split(":")
key = (splitline[0]).strip()
value = (splitline[1]).strip()
outputdict[sensor][key] = value
return outputdict
def get_temp_c_float(indict):
import re
"""
This function takes a dict of sensors output and strips
out the Units symbol and High/Crit threshold data
"""
for k in indict.keys():
for j in (indict[k]).keys():
tempfloat = re.search(r'^.(\d*\.\d*).*$', indict[k][j])
if tempfloat:
tempfloat = tempfloat.groups()[0]
indict[k][j] = float(tempfloat)
indict['Units'] = "Celcius"
return indict
if __name__ == "__main__":
d = run_process("sensors")
out = parse_sensors_output(d)
out = get_temp_c_float(out)
"""
Simply print the Temperature of Physical ID 0 (core with highest
temperature) if 'coretemp' is provided as an argument
"""
if sys.argv[-1] == "coretemp":
# Check if "Physical id 0" or "Package id 0" is produced
# This seciton needs to be tuned according to what you consider
# overall CPU Temperature.
if "Physical id 0" in out['coretemp-isa-0000'].keys():
print(out["coretemp-isa-0000"]["Physical id 0"])
elif "Package id 0" in out['coretemp-isa-0000'].keys():
print(out["coretemp-isa-0000"]["Package id 0"])
else:
import json
print(json.dumps(out, indent=2, sort_keys=True))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment