-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgoogleIP
executable file
·211 lines (169 loc) · 6.61 KB
/
googleIP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/python
#
#
# 1) Install the google documents python api
# 2) Create a spreadsheet in google documents and save it under a name
# that matches SPREADSHEET_NAME
# 3) Name the column headings of the google spreadsheet 'ip','date','time'
# 4) Edit USERNAME and PASSWD to match your login info
# 5) Make this file executable
# 6) In a terminal window, type 'crontab -e' and add this script to your
# user's crontab. ex. 56 * * * * /usr/bin/python /path_to_your_script/googleIP.py
#
### !! Dependencies !! ##
# gdata-pythong-client library
from __future__ import absolute_import, print_function, unicode_literals
import os, time,string, socket
from time import strptime
## Change These to Match Your Info!
SPREADSHEET_NAME = 'IP_addresses' # google documents spreadsheet name
# Uncomment these variables
#USERNAME = '[email protected]' # google/gmail login id
#PASSWD = 'your_password_here' # google/gmail login password
# -|- OR -|- #
# Put it in a hidden root-only, preferably encrypted, folder
# google login info looks just like (without the #s):
#gmail_address[@google_apps_domain.edu]
#super_secret_password
USER_INFO_FILE = '/root/.google_user_info'
try:
with open(USER_INFO_FILE) as f:
info = f.readlines()
USERNAME, PASSWD = info[0].strip(), info[1].strip()
except e:
print(e)
print(USER_INFO_FILE + '''USER_INFO_FILE not found''')
USERNAME = raw_input('''\nUsername? (say quit to do so)')''')
if USERNAME == 'quit':
exit(0)
BASE_DIR = '/tmp/' # Base Directory to locally save your IP info
# trailing slash required!
IP_WEBSITE = 'http://myip.xname.org/'
#IP_WEBSITE = 'whatismyip.everdot.org/ip' # alternate website?
# Time formats
date_format = '%m/%d/%Y'
time_format = '%H:%M:%S %Z'
param_delimeter = '$'
#####################################################################
###################### Function Definitions #####################
#####################################################################
def StringToDictionary(row_data):
result = {}
for param in row_data.split(param_delimeter):
name, value = param.split('=')
result[name] = value
return result
def load():
import gdata.spreadsheet.service
gd_client = gdata.spreadsheet.service.SpreadsheetsService()
gd_client.email = USERNAME
gd_client.password = PASSWD
gd_client.ProgrammaticLogin()
return gd_client
def rowToHostsFormat(row):
return '\t'.join([row.custom['ip'].text.strip(),
row.custom['host'].text.strip()]) + '\n'
def updateEtcHosts(fresh_ips):
if not fresh_ips: return
from string import whitespace
lines = []
with open('/etc/hosts', 'r') as hosts:
for line in hosts.readlines():
for i,row in enumerate(fresh_ips):
if row.custom['host'].text in line:
lines.append(rowToHostsFormat(row))
del fresh_ips[i]
break
else: #
# add any NEW hosts not previously stored to hosts before the blank line that MUST be present
if line in whitespace:
for next_ip in fresh_ips:
lines.append(rowToHostsFormat(next_ip))
fresh_ips = []
lines.append(line)
else: lines.append(line)
with open('/etc/hosts', 'w') as hosts:
for line in lines:
hosts.write(line)
def updateIP(ip, last_update_time):
hostname = socket.gethostname()
gd_client = load()
docs= gd_client.GetSpreadsheetsFeed()
spreads = []
fresh_ips = []
#Get correct spreadsheet
for i in docs.entry: spreads.append(i.title.text)
spread_number = None
for i,j in enumerate(spreads):
if j == SPREADSHEET_NAME: spread_number = i; break
else:
return None
#Get correct worksheet feed
key = docs.entry[spread_number].id.text.rsplit('/', 1)[1]
feed = gd_client.GetWorksheetsFeed(key)
wksht_id = feed.entry[0].id.text.rsplit('/', 1)[1]
feed = gd_client.GetListFeed(key,wksht_id)
#Get correct row (if it exists) AND build a list of newly updated IPs to return for updating /etc/hosts
row_index = None
for i,entry in enumerate(feed.entry):
if entry.custom['host'].text == hostname:
row_index = i
else:
this_update_time = time.mktime( strptime(entry.custom['date'].text + ' ' + entry.custom['time'].text, date_format + ' ' + time_format))
#print time.strftime(date_format + ' ' + time_format,time.localtime(this_update_time))
#print time.strftime(date_format + ' ' + time_format,time.localtime(last_update_time))
if this_update_time >= last_update_time:
fresh_ips.append(entry)
#Write data
thetime = time.strftime(time_format)
thedate = time.strftime(date_format)
row_data = StringToDictionary(param_delimeter.join(['host='+hostname, 'date='+thedate, 'time='+thetime, 'ip='+ip]))
if row_index is None:
entry = gd_client.InsertRow(row_data,key,wksht_id)
else:
entry = gd_client.UpdateRow(feed.entry[row_index],row_data)
return 1, fresh_ips
def get_last_update_time():
# Get IP from external website and update the file accordingly
path = BASE_DIR + 'CheckIP'
if os.path.exists(path):
last_update_time = os.path.getmtime(path)
os.remove(path)
else: last_update_time = 0.0 if os.stat_float_times() else 0
return last_update_time
def getnewip():
path = BASE_DIR + 'CheckIP'
os.system('wget '+IP_WEBSITE+' -t 2 --output-document='+path)
fh2 = open(path,'r')
ip = fh2.read()
fh2.close()
return ip
def getoldip():
# Read in previous IP (if it exists)
path = BASE_DIR + 'CurrentIP'
if os.path.exists(path):
fh1 = open(path,'r')
ip = fh1.read()
fh1.close()
else:
ip = ''
return ip
def saveip(ip):
path = BASE_DIR + 'CurrentIP'
fh = open(path,'w')
fh.write(ip)
fh.close()
## Executed Code
if __name__ == "__main__":
last_update_time = get_last_update_time()
newip = getnewip()
oldip = getoldip()
#if ip1 != ip2: pass
# We always want to run updateIP because it will build a list of freshly updated other IPs for updating /etc/hosts
res, fresh_ips = updateIP(newip, last_update_time)
if res == 0:
raise 'Please Create a Spreadsheet named \''+SPREADSHEET_NAME+'\' in googleDocs.'
else:
if newip != oldip:
saveip(newip)
updateEtcHosts(fresh_ips)