Last active
December 19, 2015 23:39
-
-
Save wgkoro/6036245 to your computer and use it in GitHub Desktop.
超手抜き版Webページチェッカー
HTTPでアクセスして、ステータスコードが4xx以上であればメール送信
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
""" | |
Author : wg_koro | |
Update : 2013/7/10 | |
Web page checker | |
""" | |
import urllib | |
import smtplib | |
import traceback | |
from email.MIMEText import MIMEText | |
from email.Header import Header | |
from email.Utils import formatdate | |
""" | |
メール設定 | |
""" | |
MAIL_FROM = 'piyo@aaa.com' # 送信元アドレス | |
MAIL_TO = 'fuga@bbb.net' # 送信先アドレス | |
MAIL_SUBJECT = u'タイトル' # メールタイトル | |
""" | |
送信に使うGmailアカウント設定 | |
""" | |
GMAIL_ID = 'xxx@gmail.com' # 送信に使うGmail(OR Apps)アカウントID | |
GMAIL_PASS = 'passpasspass' # 上記IDのパスワード | |
""" | |
文字エンコード | |
""" | |
ENCODE = 'ISO-2022-JP' | |
class ServiceChecker: | |
def __init__(self): | |
self.error = [] | |
self.check_list = { | |
u'ぐーぐる' : 'http://www.google.co.jp/hogehoge' | |
} | |
def check_service(self): | |
for key, url in self.check_list.items(): | |
status = self.fetch_page(url) | |
if status: | |
self.error.append('%s: %s' % (key, status)) | |
if not self.error: | |
return | |
error_list = '\n'.join(self.error) | |
msg = self.create_message(MAIL_FROM, MAIL_TO, MAIL_SUBJECT, error_list) | |
self.send(MAIL_FROM, MAIL_TO, msg) | |
def fetch_page(self, url): | |
page = urllib.urlopen(url) | |
status = page.getcode() | |
if status >= 400: | |
return status | |
return None | |
def create_message(self, from_addr, to_addr, subject, body): | |
msg = MIMEText(body, 'plain', ENCODE) | |
msg['Subject'] = Header(subject, ENCODE) | |
msg['From'] = from_addr | |
msg['To'] = to_addr | |
msg['Date'] = formatdate() | |
return msg | |
def send(self, from_addr, to_addr, msg): | |
st = smtplib.SMTP('smtp.gmail.com', 587) | |
st.ehlo() | |
st.starttls() | |
st.ehlo() | |
st.login(GMAIL_ID, GMAIL_PASS) | |
st.sendmail(from_addr, [to_addr], msg.as_string()) | |
st.close() | |
if __name__ == '__main__': | |
check = ServiceChecker() | |
check.check_service() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment