isp_ip.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from bs4 import BeautifulSoup
  2. from urllib2 import urlopen
  3. from time import strftime
  4. import time, sys
  5. def send_email(user, pwd, recipient, subject, body):
  6. import smtplib
  7. gmail_user = user
  8. gmail_pwd = pwd
  9. FROM = user
  10. TO = recipient if type(recipient) is list else [recipient]
  11. SUBJECT = subject
  12. TEXT = body
  13. # Prepare actual message
  14. message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
  15. """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
  16. try:
  17. server = smtplib.SMTP("smtp.gmail.com", 587)
  18. server.ehlo()
  19. server.starttls()
  20. server.login(gmail_user, gmail_pwd)
  21. server.sendmail(FROM, TO, message)
  22. server.close()
  23. print 'successfully sent the mail'
  24. except:
  25. print "failed to send mail"
  26. def send_ip_alert(curr_ip, old_ip):
  27. user='cigarbar@gmail.com'
  28. pwd='taipeii0i'
  29. recipient='larry1chan@gmail.com'
  30. body = 'different ip detected. Update new record at no-ip to avoid hosts not reachable\nNew: [%s] Old:[%s]\n' % (curr_ip, old_ip)
  31. subject='IP changed %s' % curr_ip
  32. send_email(user, pwd, recipient, subject, body)
  33. def isp_assigned_ip(iphist):
  34. curr_ip = None
  35. try:
  36. url = 'http://ipecho.net/plain'
  37. curr_ip = urlopen(url).read()
  38. except:
  39. return 'error getting the current ip address!'
  40. try:
  41. f = open(iphist)
  42. old_ip = f.readline()
  43. if old_ip <> curr_ip:
  44. send_ip_alert(curr_ip, old_ip)
  45. print 'different ip detected. Update new record at no-ip to avoid hosts not reachable'
  46. f.close()
  47. f = open(iphist, 'w')
  48. f.write(curr_ip)
  49. f.close()
  50. else:
  51. print 'same ip - nothing to do'
  52. except IOError:
  53. old_ip = "no previous ip record!"
  54. f = open(iphist, 'w')
  55. f.write(curr_ip)
  56. f.close()
  57. send_ip_alert(curr_ip, old_ip)
  58. if __name__ == '__main__':
  59. #send_daily_alert()
  60. if len(sys.argv) != 2:
  61. print("Usage: %s <path to iphistory.dat>" % sys.argv[0])
  62. exit(-1)
  63. isp_assigned_ip(sys.argv[1])
  64. # print allianz()
  65. #
  66. # print cn_huaxia()
  67. # print bct_funds()