sendIP.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Load IP from file def load_ip(filename): f = open(filename, 'r') ip = f.readline() return ip # Save IP def save_ip(filename, ip): f = open(filename, 'w') f.write(ip) # Get global IP. import urllib2 def get_ip(): ip = urllib2.urlopen('http://ipcheck.ieserver.net').read() return ip # Send IP by e-mail. import smtplib from email.MIMEText import MIMEText def create_message(from_addr, to_addr, subject, body): msg = MIMEText(body) msg['Subject'] = subject msg['From'] = from_addr msg['To'] = to_addr return msg def send_via_gmail(gmail_id, gmail_pw, msg): s = smtplib.SMTP('smtp.gmail.com', 587) s.ehlo() s.starttls() s.ehlo() s.login(gmail_id, gmail_pw) s.sendmail(msg['From'], msg['To'], msg.as_string()) s.close() if __name__ == '__main__': from_addr = 'hoge@gmail.com' to_addr = 'piyo@gmail.com' gmail_id = 'fuga@gmail.com' gmail_pw = 'password' ip_file = 'my_ip' cur_ip = get_ip() old_ip = load_ip(ip_file) print cur_ip print old_ip if cur_ip != old_ip: body = 'IP has changed! ' + old_ip + ' --> '+ cur_ip msg = create_message(from_addr, to_addr, 'IP', body) send_via_gmail(gmail_id, gmail_pw, msg) save_ip(ip_file, cur_ip)my_ipというファイルがないと失敗するので、あらかじめ作成しておきましょう。本当はこのへんも例外とかで処理しなきゃダメなんだろうけどね。
pythonのモジュールの充実っぷりに泣いた
返信削除デフォルトで使えるってのはすごく重要だってRubyOnRailsの作者の人も言ってましたね~
返信削除