· 9 years ago · Mar 25, 2017, 08:30 AM
1#! /usr/bin/env python
2
3
4# Check for internet connection
5
6import urllib2
7import time
8import string
9
10def internet_on():
11 try:
12 response=urllib2.urlopen('http://www.google.com/',timeout=1)
13 return True
14 except urllib2.URLError as err: pass
15 return False
16
17#loop_value = 1
18#while (loop_value == 1):
19# try:
20# urllib2.urlopen("http://www.google.com")
21# except urllib2.URLError, e:
22# time.sleep( 10 )
23# else:
24# loop_value = 0
25
26# Commands to be run if internet connection is present:
27if internet_on():
28 # Get external IP from canyouseeme.org by searching html page for an IP address
29 import urllib
30 import re
31 f = urllib.urlopen("http://myip.dnsdynamic.org/")
32 html_doc = f.read()
33 f.close()
34 m = re.search('(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)',html_doc)
35 # print html_doc
36 #print m.group(0)
37 current_ipaddress = m.group(0)
38
39 # Look at last line of ip log file
40 IPlog = open ('iplog.txt')
41 lineList = IPlog.readlines()
42 IPlog.close()
43 # print (lineList)
44 # print ("The last line is:")
45 # print (lineList[len(lineList)-1])
46 # or simply
47 # print (lineList[-1])
48 # print current_ipaddress
49
50 # See if current IP has changed from last logged
51 if current_ipaddress + "n" <> lineList[-1]:
52 #Append ip address to ip log file
53 f = open('iplog.txt','a')
54 localtime = time.asctime( time.localtime(time.time()) )
55 f.write(localtime + "n" + current_ipaddress + "n")
56 # python will convert n to os.linesep
57 f.close()
58
59 # Mail new ip
60 import smtplib
61 smtp_server = 'smtp.gmail.com'
62 smtp_port = 587
63 sender = '****@gmail.com'
64 # recipients = ["*****2001@hotmail.com", "john@***.com"]
65 recipients = ["*****@***.com"]
66
67
68 subject = 'SERVER ALERT'
69 body = 'Server IP address has changed to: ' + current_ipaddress
70 password = '**********************'
71 smstext = body
72 body = "" + body + ""
73
74 headers = ["From: " + sender,
75 "Subject: " + subject,
76 #"To: " + "Fred and John",
77 "To: " + "John",
78 "MIME-Version: 1.0",
79 "Content-Type: text/html"]
80 headers = "rn".join(headers)
81
82 session = smtplib.SMTP(smtp_server, smtp_port)
83
84 session.ehlo()
85 session.starttls()
86 session.ehlo
87 session.login(sender, password)
88
89 session.sendmail(sender, recipients, headers + "rnrn" + body)
90 session.quit()
91
92
93 # Google Voice SMS send
94 import pygvoicelib
95 conn = pygvoicelib
96
97 username="**************"
98 apppass="****************************"
99 auth_token="***********************************"
100 client = conn.GoogleVoice(username,apppass,auth_token,rnr_se)
101 #phone number below
102 client.sms('1212*******',smstext)