? GR0V Shell

GR0V shell

Linux server122.web-hosting.com 4.18.0-513.18.1.lve.el8.x86_64 #1 SMP Thu Feb 22 12:55:50 UTC 2024 x86_64

Path : /lib64/nagios/plugins/nccustom/
File Upload :
Current File : //lib64/nagios/plugins/nccustom/check_cpu_temperature.py

#!/usr/libexec/platform-python
# -*- coding: utf-8 -*-


import re
import json
import argparse
from subprocess import Popen, PIPE


class CpuTemperature(object):

    def __init__(self):
        self.info = None
        self.model = None
        self.vendor = None
        self.revision = None
        self.temperature = dict()

    def get_vendor(self):
        cmd = '/usr/bin/env lscpu'
        _raw = self.execute(cmd)
        for line in _raw.split("\n"):
            if 'Model name:' in line:
                self.info = line
                if 'intel' in line.lower():
                    self.vendor = 'Intel'
                elif "AMD" in line.upper():
                    self.vendor = 'AMD'
                else:
                    raise RuntimeError("CPU's vendor hasn't defined.")

    def get_details(self):
        if self.vendor == 'Intel':
            info = self.info.split("@")[0].split()
            self.revision = info[-1]
            self.model = info[-2]
        else:
            infosplitted = self.info.split()
            if "EPYC" in self.info.upper():
                self.model = "EPYC_" + str(infosplitted[infosplitted.index('EPYC') + 1])
            elif "ROME" in self.info.upper():
                self.model = "ROME_" + str(infosplitted[infosplitted.index('ROME') + 1])
            else:
                self.model = "_".join(infosplitted[-2:])

    def get_temperature(self, data):
        if self.vendor == 'Intel':
            re_intel = re.compile(r"(Physical|Package)\s+id\s+(\d+):\s*([+-]?\d*\.?\d*)", re.I)
            matches = re_intel.finditer(data)
            for find in matches:
                proc_num = find.group(2)
                proc_temp = find.group(3)
                self.temperature[proc_num] = float(proc_temp)
        else:
            proc_num = 0
            re_amd = re.compile(r"k10temp-pci.*\n(temp|Tctl)\d*:\s*([+-]?\d*\.?\d*)", re.I)
            matches = re_amd.finditer(data)
            for find in matches:
                proc_temp = find.group(2)
                self.temperature[proc_num] = float(proc_temp)
                proc_num += 1

    def sensors(self):
        cmd = '/usr/bin/env sensors -A'
        return self.execute(cmd)

    @staticmethod
    def execute(cmd):
        process = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        stdout, error = process.communicate()
        if error:
            raise RuntimeError(error.decode("utf-8"))
        return stdout.decode("utf-8")


def load_config(cfg):
    with open(cfg) as f:
        try:
            return json.loads(f.read())
        except json.JSONDecodeError as err:
            print("Error decoding JSON in the configuration file: {}".format(err))
            raise SystemExit(2)
        except Exception as err:
            print(err)
            raise SystemExit(2)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="CPU Temperature Check")
    parser.add_argument("-c", "--config", required=True, help="Path to the configuration file")
    parser.add_argument("-v", "--verbose", action="store_true", help="More verbose output")
    args = parser.parse_args()

    try:
        config = load_config(args.config)
    except IOError as err:
        print("Error loading the configuration file: {}".format(err))
        raise SystemExit(2)

    cpu = CpuTemperature()

    try:
        cpu.get_vendor()
    except RuntimeError as err:
        print(err)
        raise SystemExit(2)
    if args.verbose:
        print("CPU Vendor: {}".format(cpu.vendor))

    cpu.get_details()
    if args.verbose:
        print("CPU Model: {}".format(cpu.model))

    try:
        raw = cpu.sensors()
    except RuntimeError as err:
        print(err)
        raise SystemExit(2)
    if args.verbose:
        print("-=-=-=-=-=-=-=-=-=-=-=-=-")
        print("Sensors Raw Output:\n")
        print(raw)
        print("-=-=-=-=-=-=-=-=-=-=-=-=-")

    cpu.get_temperature(raw)

    crit = []
    warn = []
    ok = []

    try:
        if cpu.vendor == 'Intel':
            max_temp = float(config.get(cpu.vendor, {}).get(cpu.revision, {}).get(cpu.model, 0))
        else:
            max_temp = float(config.get(cpu.vendor, {}).get(cpu.model, 0))
    except ValueError:
        print("Invalid temperature value in configuration for {}: {}".format(cpu.vendor, cpu.model))
        raise SystemExit(2)

    for p, t in cpu.temperature.items():
        if float(t) >= max_temp:
            crit.append("CPU {}: temperature +{}C".format(p, t))
        elif float(t) >= max_temp - 5:
            warn.append("CPU {}: temperature +{}C".format(p, t))
        else:
            ok.append("CPU {}: temperature +{}C".format(p, t))

    if crit:
        print("; ".join(crit))
        raise SystemExit(2)
    elif warn:
        print("; ".join(warn))
        raise SystemExit(1)
    else:
        print("; ".join(ok))
        raise SystemExit(0)

T1KUS90T
  root-grov@198.54.114.191:~$