Created
June 10, 2012 07:29
-
-
Save higebu/2904386 to your computer and use it in GitHub Desktop.
E-mail notification of changes in global IP address
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/python | |
# -*- coding: utf-8 -*- | |
import os | |
import urllib | |
import smtplib | |
from email.MIMEText import MIMEText | |
from email.Utils import formatdate | |
import datetime | |
def get_global_ip(): | |
url = "http://higebu.com/remote_addr.php" | |
res = urllib.urlopen(url) | |
ip = res.readline() | |
return ip | |
def create_message(from_addr, to_addr, subject, body): | |
msg = MIMEText(body) | |
msg['Subject'] = subject | |
msg['From'] = from_addr | |
msg['To'] = ','.join( to_addr ) | |
msg['Date'] = formatdate() | |
return msg | |
def send_via_gmail(from_addr, to_addr, msg): | |
s = smtplib.SMTP('smtp.gmail.com', 587) | |
s.ehlo() | |
s.starttls() | |
s.ehlo() | |
s.login('your-account@gmail.com', 'password') | |
s.sendmail(from_addr, to_addr, msg.as_string()) | |
s.close() | |
def main(): | |
new_ip = get_global_ip() | |
old_ip = '' | |
if os.path.exists('ip.txt'): | |
f = open('ip.txt', 'r') | |
old_ip = f.readline() | |
if new_ip != old_ip: | |
from_addr = 'your-account@gmail.com' | |
to_addr = ['to_addr1@example.com', 'to_addr2@example.com'] | |
subject = 'Global IP has been changed at ' + datetime.datetime..now().strftime(u'%Y/%m/%d %H:%M:%S') | |
body = new_ip | |
msg = create_message(from_addr, to_addr, subject, body) | |
send_via_gmail(from_addr, to_addr, msg) | |
f = open('ip.txt', 'w') | |
f.write(new_ip) | |
f.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment