· 6 years ago · Oct 10, 2019, 04:24 AM
1from smtplib import SMTP
2from time import strftime, gmtime
3from urllib import request
4import datetime
5import re
6
7
8
9url = "http://checkip.dyndns.org"
10results = request.urlopen(url).read().decode()
11currentIP = re.findall(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", results)[0]
12
13debuglevel = 0
14
15timestamp=strftime("%B %d, %Y -- %I:%M", gmtime())
16
17with open('lastip', 'r') as f:
18 lastIP = f.read()
19
20if lastIP != currentIP:
21
22 f1 = request.urlopen("https://dynamicdns.park-your-domain.com/update?host=@&domain=**************&password=**************")
23 s1 = f1.read()
24 f1.close()
25
26 a1 = "{0}: @ RETURNED: {1}{2}".format(timestamp,s1,'\n')
27
28 with open('dnsupdate.log', 'a+') as l:
29 l.write(a1)
30
31 f1 = request.urlopen("https://dynamicdns.park-your-domain.com/update?host=@&domain=**************&password=**************")
32 s1 = f1.read()
33 f1.close()
34
35 a1 = "{0}: @ RETURNED: {1}{2}".format(timestamp,s1,'\n')
36
37 with open('dnsupdate.log', 'a+') as l:
38 l.write(a1)
39
40 f1 = request.urlopen("https://dynamicdns.park-your-domain.com/update?host=@&domain=**************&password=**************")
41 s1 = f1.read()
42 f1.close()
43
44 a1 = "{0}: @ RETURNED: {1}{2}".format(timestamp,s1,'\n')
45
46 with open('dnsupdate.log', 'a+') as l:
47 l.write(a1)
48
49 print('IP has changed.')
50
51 smtp = SMTP()
52 smtp.set_debuglevel(debuglevel)
53 smtp.connect('smtp.gmail.com', 587)
54 smtp.ehlo()
55 smtp.starttls()
56 smtp.ehlo()
57 smtp.login('**************@gmail.com', '**************')
58
59 from_addr = "************** <**************@gmail.com>"
60 to_addrs = ("**************@vtext.com","**************@vtext.com","**************@gmail.com")
61
62 subj = "**************"
63 date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
64
65 message_text = "The IP has changed from {0} to {1}.".format( lastIP, currentIP )
66
67 for to_addr in to_addrs:
68 msg = "From: {0}\nTo: {1}\nSubject: {2}\nDate: {3}\n\n{4}".format( from_addr, to_addr, subj, date, message_text )
69 smtp.sendmail(from_addr, to_addr, msg)
70
71 smtp.quit()
72
73 with open('lastip', 'w') as f:
74 f.write(currentIP)
75
76else:
77 print('IP has not changed')
78
79 a1 = "{0}: @ RETURNED: NO CHANGE ({1}){2}".format(timestamp,currentIP,'\n')
80
81 with open('dnsupdate.log', 'a+') as l:
82 l.write(a1)