LoginSignup
1
1

More than 5 years have passed since last update.

DBサーバーが動いているか確認するpythonスクリプト

Last updated at Posted at 2016-08-21

前提
・python3
・PyMySQLモジュールインストール済み

やりたいこと:
・ある特定のDBが動いているかチェックして、動かなかったらエラーメールする
・cronjob等で2分ごとスクリプトを実行する

#!/usr/bin/python

import os, sys, smtplib
import pymysql.cursors
from email.mime.text import MIMEText

def send_mail(title, msg, from_addr, to_addr, cc_addrs=None):
    if not from_addr or not to_addr:
        return

    new_mail = MIMEText(msg)
    new_mail["Subject"] = title
    new_mail["From"] = from_addr
    new_mail["To"] = to_addr

    if cc_addrs != None:
        if isinstance(cc_addrs, str):
            new_mail["Cc"] = cc_addrs
        elif isinstance(cc_addrs, list) and cc_addrs != []:
            new_mail["Cc"] = ','.join(cc_addrs)

    smtp = smtplib.SMTP('localhost')
    smtp.send_message(new_mail)
    smtp.quit()

def send_default_error_mail(error_txt=None):
    error_msg = "Error, please make some action to recover."
    if error_msg:
        error_msg = error_msg + "Error: " + error_txt
    send_mail(
        "Database connection check",
        error_msg,
        "送信元メールアドレス",
        "送信先メールアドレス"
    )
    connection = None
try:
    connection = pymysql.connect(
        host='ホスト',
        user='ユーザ名',
        password='パスワード',
        db='DB名',
        charset='utf8',
        cursorclass=pymysql.cursors.DictCursor)

    if not connection:
        send_default_error_mail()

    with connection.cursor() as cursor:
        sql = "SELECT 1=1"
        cursor.execute(sql)
        results = cursor.fetchall()
        if not results or len(results) == 0:
            send_default_error_mail()
except:
    ex, ms, tb = sys.exc_info()
    error_txt = str(ms)
    send_default_error_mail(error_txt)
finally:
    if connection:
        connection.close
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1