CPU温度をメールで通知するスクリプト


RaspberryPiのCPU温度をメールで通知するスクリプトです。
RaspberryPiのCPU温度は、下記のコマンドで取得できます。

$ cat /sys/class/thermal/thermal_zone0/temp
41698

取得した値は1000倍された値なので、1000で割ると現在のCPU温度が取得できます。
上記の場合は約41.6度となります。

せっかくなので取得したCPU温度をメールで送るためのスクリプトを書きたいと思います。
Pythonを使用してメールを送るためにPython 公式「email 使用例」を参考にしました。
若干自分用にカスタマイズしていますが、下記のコードで、CPU温度が50度以上になったらメールを送信することができます。送信サーバーはGmailを使用しています。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import commands
import datetime
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate

TempMax = 50
now = datetime.datetime.utcnow()
logdatetime= now.strftime("%Y-%m-%d %H:%M:%S")

command = "cat /sys/class/thermal/thermal_zone0/temp"
measure_temp = commands.getoutput(command)
measure_temp =int( measure_temp) / 1000

if measure_temp > TempMax:
  #mail setting
  from_address = ""#※送信元メールアドレス
  to_address = ""#※送信先メールアドレス

  charset = "ISO-2022-JP"
  #title
  subject = u"raspilapse is operation"
  #main
  text = str(measure_temp) + "'C" + "\n datetime " + logdatetime

  msg = MIMEText(text.encode(charset),"plain",charset)
  msg["Subject"] = Header(subject,charset)
  msg["From"] = from_address
  msg["To"] = to_address
  msg["Date"] = formatdate(localtime=True)

  smtp = smtplib.SMTP("smtp.gmail.com", 587)#※GmailのSMTPサーバーを指定
  smtp.ehlo()
  smtp.starttls()
  smtp.ehlo()
  smtp.login("アカウント", "パスワード")#※smtpのアカウントとパスワードを指定 例)アカウント:○○○.gmail.com パス:123456
  smtp.sendmail(from_address,to_address,msg.as_string())
  smtp.close()

上記のファイルを保存して、cronを使って毎分実行すればCPU温度の管理プログラムの出来上がりです。
スポンサード・リンク


日本で一番簡単にビットコインが買える取引所 coincheck bitcoin