forked from StevenBlack/hosts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdateHostsFile.py
438 lines (377 loc) · 15.2 KB
/
updateHostsFile.py
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
#!/usr/bin/env python
# Script by Ben Limmer
# https://github.com/l1m5
#
# This Python script will combine all the host files you provide
# as sources into one, unique host file to keep you internet browsing happy.
# pylint: disable=invalid-name
# pylint: disable=bad-whitespace
# Making Python 2 compatible with Python 3
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import platform
import re
import shutil
import string
import subprocess
import sys
import tempfile
import time
import glob
import argparse
# zip files are not used actually, support deleted
# StringIO is not needed in Python 3
# Python 3 works differently with urlopen
# Supporting urlopen in Python 2 and Python 3
try:
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
# This function handles both Python 2 and Python 3
def getFileByUrl(url):
try:
f = urlopen(url)
return f.read().decode("UTF-8")
except:
print ("Problem getting file: ", url)
# raise
# In Python 3 "print" is a function, braces are added everywhere
# Detecting Python 3 for version-dependent implementations
Python3 = False
cur_version = sys.version_info
if cur_version >= (3, 0):
Python3 = True
# This function works in both Python 2 and Python 3
def myInput(msg = ""):
if Python3:
return input(msg)
else:
return raw_input(msg)
# Cross-python writing function
def writeData(f, data):
if Python3:
f.write(bytes(data, 'UTF-8'))
else:
f.write(str(data).encode('UTF-8'))
# This function doesn't list hidden files
def listdir_nohidden(path):
return glob.glob(os.path.join(path, '*'))
# Project Settings
BASEDIR_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_PATH = os.path.join(BASEDIR_PATH, 'data')
DATA_FILENAMES = 'hosts'
UPDATE_URL_FILENAME = 'update.info'
SOURCES = listdir_nohidden(DATA_PATH)
README_TEMPLATE = os.path.join(BASEDIR_PATH, 'readme_template.md')
README_FILE = os.path.join(BASEDIR_PATH, 'readme.md')
WHITELIST_FILE = os.path.join(BASEDIR_PATH, 'whitelist')
# Exclusions
EXCLUSION_PATTERN = '([a-zA-Z\d-]+\.){0,}' #append domain the end
EXCLUSIONS = []
# Common domains to exclude
COMMON_EXCLUSIONS = ['hulu.com']
# Global vars
exclusionRegexs = []
numberOfRules = 0
auto = False
targetIP = "0.0.0.0"
def main():
parser = argparse.ArgumentParser(description="Creates an amalgamated hosts file from hosts stored in data subfolders.")
parser.add_argument("--auto", "-a", dest="auto", default=False, action='store_true', help="Run without prompting.")
parser.add_argument("--ip", "-i", dest="targetIP", default="0.0.0.0", help="Target IP address. Default is 0.0.0.0")
args = parser.parse_args()
global auto, targetIP
auto = args.auto
targetIP = args.targetIP
promptForUpdate()
promptForExclusions()
mergeFile = createInitialFile()
removeOldHostsFile()
finalFile = removeDupsAndExcl(mergeFile)
finalizeFile(finalFile)
updateReadme(numberOfRules)
printSuccess('Success! Your new hosts file has been prepared.\nIt contains ' +
"{:,}".format(numberOfRules) + ' unique entries.')
promptForMove(finalFile)
# Prompt the User
def promptForUpdate():
# Create hosts file if it doesn't exists
if not os.path.isfile(os.path.join(BASEDIR_PATH, 'hosts')):
try:
open(os.path.join(BASEDIR_PATH, 'hosts'), 'w+').close()
except:
printFailure("ERROR: No 'hosts' file in the folder, try creating one manually")
response = "yes" if auto else query_yes_no("Do you want to update all data sources?")
if response == "yes":
updateAllSources()
else:
if not auto:
print ("OK, we\'ll stick with what we\'ve got locally.")
def promptForExclusions():
response = "no" if auto else query_yes_no("Do you want to exclude any domains?\n" +
"For example, hulu.com video streaming must be able to access " +
"its tracking and ad servers in order to play video.")
if response == "yes":
displayExclusionOptions()
else:
if not auto:
print ("OK, we\'ll only exclude domains in the whitelist.")
def promptForMoreCustomExclusions():
response = query_yes_no("Do you have more domains you want to enter?")
if response == "yes":
return True
else:
return False
def promptForMove(finalFile):
response = "no" if auto else query_yes_no("Do you want to replace your existing hosts file " +
"with the newly generated file?")
if response == "yes":
moveHostsFileIntoPlace(finalFile)
else:
return False
# End Prompt the User
# Exclusion logic
def displayExclusionOptions():
for exclusionOption in COMMON_EXCLUSIONS:
response = query_yes_no("Do you want to exclude the domain " + exclusionOption + " ?")
if response == "yes":
excludeDomain(exclusionOption)
else:
continue
response = query_yes_no("Do you want to exclude any other domains?")
if response == "yes":
gatherCustomExclusions()
def gatherCustomExclusions():
while True:
# Cross-python Input
domainFromUser = myInput("Enter the domain you want to exclude (e.g. facebook.com): ")
if isValidDomainFormat(domainFromUser):
excludeDomain(domainFromUser)
if promptForMoreCustomExclusions() is False:
return
def excludeDomain(domain):
exclusionRegexs.append(re.compile(EXCLUSION_PATTERN + domain))
def matchesExclusions(strippedRule):
strippedDomain = strippedRule.split()[1]
for exclusionRegex in exclusionRegexs:
if exclusionRegex.search(strippedDomain):
return True
return False
# End Exclusion Logic
# Update Logic
def updateAllSources():
for source in SOURCES:
updateURL = getUpdateURLFromFile(source)
if updateURL is None:
continue
print ("Updating source " + os.path.basename(source) + " from " + updateURL)
# Cross-python call
updatedFile = getFileByUrl(updateURL)
try:
updatedFile = updatedFile.replace('\r', '') #get rid of carriage-return symbols
# This is cross-python code
dataFile = open(os.path.join(DATA_PATH, source, DATA_FILENAMES), 'wb')
writeData(dataFile, updatedFile)
dataFile.close()
except:
print ("Skipping.")
def getUpdateURLFromFile(source):
pathToUpdateFile = os.path.join(DATA_PATH, source, UPDATE_URL_FILENAME)
if os.path.exists(pathToUpdateFile):
updateFile = open(pathToUpdateFile, 'r')
retURL = updateFile.readline().strip()
updateFile.close()
else:
retURL = None
printFailure('Warning: Can\'t find the update file for source ' + source + '\n' +
'Make sure that there\'s a file at ' + pathToUpdateFile)
return retURL
# End Update Logic
# File Logic
def createInitialFile():
mergeFile = tempfile.NamedTemporaryFile()
for source in SOURCES:
curFile = open(os.path.join(DATA_PATH, source, DATA_FILENAMES), 'r')
#Done in a cross-python way
writeData(mergeFile, curFile.read())
return mergeFile
def removeDupsAndExcl(mergeFile):
global numberOfRules
if os.path.isfile(WHITELIST_FILE):
with open(WHITELIST_FILE, "r") as ins:
for line in ins:
EXCLUSIONS.append(line)
# Another mode is required to read and write the file in Python 3
finalFile = open(os.path.join(BASEDIR_PATH, 'hosts'), 'r+b')
mergeFile.seek(0) # reset file pointer
hostnames = set()
hostnames.add("localhost")
for line in mergeFile.readlines():
write = 'true'
# Explicit encoding
line = line.decode("UTF-8")
# replace tabs with space
line = line.replace('\t+', ' ')
# Testing the first character doesn't require startswith
if line[0] == '#' or re.match(r'^\s*$', line[0]):
# Cross-python write
writeData(finalFile, line)
continue
if '::1' in line:
continue
strippedRule = stripRule(line) #strip comments
if len(strippedRule) == 0:
continue
if matchesExclusions(strippedRule):
continue
hostname, normalizedRule = normalizeRule(strippedRule) # normalize rule
for exclude in EXCLUSIONS:
if exclude in line:
write = 'false'
break
if normalizedRule and (hostname not in hostnames) and (write == 'true'):
writeData(finalFile, normalizedRule)
hostnames.add(hostname)
numberOfRules += 1
mergeFile.close()
return finalFile
def normalizeRule(rule):
result = re.search(r'^[ \t]*(\d+\.\d+\.\d+\.\d+)\s+([\w\.-]+)(.*)', rule)
if result:
hostname, suffix = result.group(2,3)
hostname = hostname.lower().strip() # explicitly lowercase and trim the hostname
if suffix is not '':
# add suffix as comment only, not as a separate host
return hostname, "%s %s #%s\n" % (targetIP, hostname, suffix)
else:
return hostname, "%s %s\n" % (targetIP, hostname)
print ("==>%s<==" % rule)
return None, None
def finalizeFile(finalFile):
writeOpeningHeader(finalFile)
finalFile.close()
# Some sources put comments around their rules, for accuracy we need to strip them
# the comments are preserved in the output hosts file
def stripRule(line):
splitLine = line.split()
if len(splitLine) < 2 :
# just return blank
return ''
else:
return splitLine[0] + ' ' + splitLine[1]
def writeOpeningHeader(finalFile):
global numberOfRules
finalFile.seek(0) #reset file pointer
fileContents = finalFile.read() #save content
finalFile.seek(0) #write at the top
writeData(finalFile, '# This file is a merged collection of hosts from reputable sources,\n')
writeData(finalFile, '# with a dash of crowd sourcing via Github\n#\n')
writeData(finalFile, '# Latest version of this file: https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts\n')
writeData(finalFile, '# Project home page: https://github.com/StevenBlack/hosts\n#\n')
writeData(finalFile, '# ===============================================================\n')
writeData(finalFile, '\n')
writeData(finalFile, '127.0.0.1 localhost\n')
writeData(finalFile, '::1 localhost\n')
writeData(finalFile, '\n')
preamble = os.path.join(BASEDIR_PATH, "myhosts")
if os.path.isfile(preamble):
with open(preamble, "r") as f:
writeData(finalFile, f.read())
finalFile.write(fileContents)
def updateReadme(numberOfRules):
with open(README_FILE, "wt") as out:
for line in open(README_TEMPLATE):
out.write(line.replace('@NUM_ENTRIES@', "{:,}".format(numberOfRules)))
def moveHostsFileIntoPlace(finalFile):
if os.name == 'posix':
print ("Moving the file requires administrative privileges. " +
"You might need to enter your password.")
if subprocess.call(["/usr/bin/sudo", "cp", os.path.abspath(finalFile.name), "/etc/hosts"]):
printFailure("Moving the file failed.")
print ("Flushing the DNS Cache to utilize new hosts file...")
if platform.system() == 'Darwin':
if subprocess.call(["/usr/bin/sudo", "killall", "-HUP", "mDNSResponder"]):
printFailure("Flushing the DNS Cache failed.")
else:
if os.path.isfile("/etc/rc.d/init.d/nscd"):
if subprocess.call(["/usr/bin/sudo", "/etc/rc.d/init.d/nscd", "restart"]):
printFailure("Flushing the DNS Cache failed.")
if os.path.isfile("/usr/lib/systemd/system/NetworkManager.service"):
if subprocess.call(["/usr/bin/sudo", "/usr/bin/systemctl", "restart", "NetworkManager.service"]):
printFailure("Flushing the DNS Cache failed.")
if os.path.isfile("/usr/lib/systemd/system/wicd.service"):
if subprocess.call(["/usr/bin/sudo", "/usr/bin/systemctl", "restart", "wicd.service"]):
printFailure("Flushing the DNS Cache failed.")
elif os.name == 'nt':
print ("Automatically moving the hosts file in place is not yet supported.")
print ("Please move the generated file to %SystemRoot%\system32\drivers\etc\hosts")
def removeOldHostsFile(): # hotfix since merging with an already existing hosts file leads to artefacts and duplicates
oldFilePath = os.path.join(BASEDIR_PATH, 'hosts')
open(oldFilePath, 'a').close() # create if already removed, so remove wont raise an error
backupFilePath = os.path.join(BASEDIR_PATH, 'hosts-{0}'.format(time.strftime("%c")))
shutil.copyfile(oldFilePath, backupFilePath) # make a backup copy, marking the date in which the list was updated
os.remove(oldFilePath)
open(oldFilePath, 'a').close() # create new empty hostsfile
# End File Logic
# Helper Functions
## {{{ http://code.activestate.com/recipes/577058/ (r2)
def query_yes_no(question, default = "yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
valid = {"yes":"yes", "y":"yes", "ye":"yes",
"no":"no", "n":"no"}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while 1:
sys.stdout.write(colorize(question, colors.PROMPT) + prompt)
# Changed to be cross-python
choice = myInput().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
printFailure("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
## end of http://code.activestate.com/recipes/577058/ }}}
def isValidDomainFormat(domain):
if domain == '':
print ("You didn\'t enter a domain. Try again.")
return False
domainRegex = re.compile("www\d{0,3}[.]|https?")
if domainRegex.match(domain):
print ("The domain " + domain + " is not valid. " +
"Do not include www.domain.com or http(s)://domain.com. Try again.")
return False
else:
return True
# Colors
class colors:
PROMPT = '\033[94m'
SUCCESS = '\033[92m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def colorize(text, color):
return color + text + colors.ENDC
def printSuccess(text):
print (colorize(text, colors.SUCCESS))
def printFailure(text):
print (colorize(text, colors.FAIL))
# End Helper Functions
if __name__ == "__main__":
main()