Advertisement
Guest User

dynip.py

a guest
Jun 23rd, 2012
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. import urllib
  2. import smtplib
  3.  
  4. # Emails new ip address when it changes via gmail
  5. # This is designed to be used with an OS scheduler
  6. # The url is not to be used more often than ever 300 seconds
  7. def get_ip():
  8.     # Queries url to receive external ip address
  9.     ipurl = 'http://automation.whatismyip.com/n09230945.asp'
  10.     return urllib.urlopen(ipurl).readlines()[0]
  11.  
  12. def send_new_ip(ip):
  13.     msg = "New ip address is " + ip
  14.     # From and to email addresses
  15.     fromaddr = '[email protected]'
  16.     toaddr = '[email protected]'
  17.    
  18.     #gmail credentials
  19.     username = 'username'
  20.     password = 'password'
  21.  
  22.     #send email
  23.     server = smtplib.SMTP('smtp.gmail.com:587')
  24.     server.starttls()
  25.     server.login(username,password)
  26.     server.sendmail(fromaddr, toaddr, msg)
  27.     server.quit()
  28.     print "Email sent to " + toaddr
  29.  
  30. #writes ip to <filename>
  31. def write_ip(ip, filename):
  32.     FILE = open(filename,'w')
  33.     FILE.write(ip + '\n')
  34.     FILE.close()
  35.  
  36. ip = get_ip()
  37. filename = 'ipaddress.txt'
  38.  
  39. try:
  40.     FILE = open(filename,'r')
  41.     old_ip = FILE.read().strip()
  42.     FILE.close()
  43.  
  44.     # if new ip, sends email and replaces <filename>
  45.     if ip != old_ip:
  46.         send_new_ip(ip)
  47.         write_ip(ip, filename)
  48.     else:
  49.         exit
  50.  
  51. # if <filename> does not exist, creates it and sends email
  52. except:
  53.     write_ip(ip, filename)
  54.     send_new_ip(ip)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement