update_hosts.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import sys
  5. import re
  6. import socket
  7. import getopt
  8. import threading
  9. import subprocess
  10. import shlex
  11. import time
  12. import select
  13. blackhole = (
  14. '10::2222',
  15. '101::1234',
  16. '2001::212',
  17. '2001:da8:112::21ae',
  18. '2003:ff:1:2:3:4:5fff:6',
  19. '2003:ff:1:2:3:4:5fff:7',
  20. '2003:ff:1:2:3:4:5fff:8',
  21. '2003:ff:1:2:3:4:5fff:9',
  22. '2003:ff:1:2:3:4:5fff:10',
  23. '2003:ff:1:2:3:4:5fff:11',
  24. '2003:ff:1:2:3:4:5fff:12',
  25. '21:2::2',
  26. '2123::3e12',
  27. '159.106.121.75',
  28. '202.181.7.85',
  29. '203.98.7.65',
  30. '243.185.187.39',
  31. '37.61.54.158',
  32. '4.36.66.178',
  33. '46.82.174.68',
  34. '59.24.3.173',
  35. '64.33.88.161',
  36. '78.16.49.15',
  37. '8.7.198.45',
  38. '93.46.8.89',
  39. )
  40. dns = {
  41. 'google_a': '2001:4860:4860::8888',
  42. 'google_b': '2001:4860:4860::8844',
  43. 'he_net': '2001:470:20::2',
  44. 'lax_he_net': '2001:470:0:9d::2'
  45. }
  46. config = {
  47. 'dns': dns['google_b'],
  48. 'infile': '',
  49. 'outfile': '',
  50. 'querytype': 'aaaa',
  51. 'cname': False,
  52. 'threadnum': 10
  53. }
  54. hosts = []
  55. done_num = 0
  56. thread_lock = threading.Lock()
  57. running = True
  58. class worker_thread(threading.Thread):
  59. def __init__(self, start_pt, end_pt):
  60. threading.Thread.__init__(self)
  61. self.start_pt = start_pt
  62. self.end_pt = end_pt
  63. def run(self):
  64. global hosts, done_num
  65. for i in range(self.start_pt, self.end_pt):
  66. if not running: break
  67. line = hosts[i].strip()
  68. if line == '' or line[0:2] == '##':
  69. hosts[i] = line + '\r\n'
  70. with thread_lock: done_num += 1
  71. continue
  72. # uncomment line
  73. line = line.lstrip('#')
  74. # split comment that appended to line
  75. comment = ''
  76. p = line.find('#')
  77. if p > 0:
  78. comment = line[p:]
  79. line = line[:p]
  80. arr = line.split()
  81. if len(arr) == 1:
  82. domain = arr[0]
  83. else:
  84. domain = arr[1]
  85. flag = False
  86. if validate_domain(domain):
  87. cname, ip = query_domain(domain, False)
  88. if ip == '' or ip in blackhole:
  89. cname, ip = query_domain(domain, True)
  90. if ip:
  91. flag = True
  92. arr[0] = ip
  93. if len(arr) == 1:
  94. arr.append(domain)
  95. if config['cname'] and cname:
  96. arr.append('#' + cname)
  97. else:
  98. if comment:
  99. arr.append(comment)
  100. if not flag:
  101. arr[0] = '#' + arr[0]
  102. if comment:
  103. arr.append(comment)
  104. hosts[i] = ' '.join(arr)
  105. hosts[i] += '\r\n'
  106. with thread_lock: done_num += 1
  107. class watcher_thread(threading.Thread):
  108. def run(self):
  109. total_num = len(hosts)
  110. wn = int(config['threadnum'])
  111. if wn > total_num:
  112. wn = total_num
  113. print "There are %d threads working..." % wn
  114. print "Press 'Enter' to exit.\n"
  115. while True:
  116. if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
  117. raw_input()
  118. print 'Waiting threads to exit...'
  119. global running
  120. with thread_lock:
  121. running = False
  122. break
  123. dn = done_num
  124. outbuf = "Total: %d lines, Done: %d lines, Ratio: %d %%.\r"\
  125. % (total_num, dn, dn * 100 / total_num)
  126. print outbuf,
  127. sys.stdout.flush()
  128. if dn == total_num:
  129. print outbuf
  130. break
  131. time.sleep(1)
  132. def query_domain(domain, tcp):
  133. cmd = "dig +short +time=2 -6 %s @'%s' '%s'"\
  134. % (config['querytype'], config['dns'], domain)
  135. if tcp:
  136. cmd = cmd + ' +tcp'
  137. proc = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
  138. out, _ = proc.communicate()
  139. outarr = out.splitlines()
  140. cname = ip = ''
  141. for v in outarr:
  142. if cname == '' and validate_domain(v[:-1]):
  143. cname = v[:-1]
  144. if ip == '' and validate_ip_addr(v):
  145. ip = v
  146. break
  147. return (cname, ip)
  148. def validate_domain(domain):
  149. pattern = '^((?!-)[*A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$'
  150. p = re.compile(pattern)
  151. m = p.match(domain)
  152. if m:
  153. return True
  154. else:
  155. return False
  156. def validate_ip_addr(ip_addr):
  157. if ':' in ip_addr:
  158. try:
  159. socket.inet_pton(socket.AF_INET6, ip_addr)
  160. return True
  161. except socket.error:
  162. return False
  163. else:
  164. try:
  165. socket.inet_pton(socket.AF_INET, ip_addr)
  166. return True
  167. except socket.error:
  168. return False
  169. def print_help():
  170. print '''usage: update_hosts [OPTIONS] FILE
  171. A simple multi-threading tool used to update hosts file.
  172. Options:
  173. -h, --help show this help message and exit
  174. -s DNS set another dns server, default: 2001:4860:4860::8844
  175. -o OUT_FILE ouput file, default: inputfilename.out
  176. -t QUERY_TYPE dig command query type, defalut: aaaa
  177. -c, --cname write canonical name into hosts file
  178. -n THREAD_NUM set the number of worker threads, default: 10
  179. '''
  180. def get_config():
  181. shortopts = 'hs:o:t:n:c'
  182. longopts = ['help', 'cname']
  183. try:
  184. optlist, args = getopt.gnu_getopt(sys.argv[1:], shortopts, longopts)
  185. except getopt.GetoptError as e:
  186. print e, '\n'
  187. print_help()
  188. sys.exit(1)
  189. global config
  190. for key, value in optlist:
  191. if key == '-s':
  192. config['dns'] = value
  193. elif key == '-o':
  194. config['outfile'] = value
  195. elif key == '-t':
  196. config['querytype'] = value
  197. elif key in ('-c', '--cname'):
  198. config['cname'] = True
  199. elif key == '-n':
  200. config['threadnum'] = int(value)
  201. elif key in ('-h', '--help'):
  202. print_help()
  203. sys.exit(0)
  204. if len(args) != 1:
  205. print "You must specify the input hosts file (only one)."
  206. sys.exit(1)
  207. config['infile'] = args[0]
  208. if config['outfile'] == '':
  209. config['outfile'] = config['infile'] + '.out'
  210. def main():
  211. get_config()
  212. dig_path = '/usr/bin/dig'
  213. if not os.path.isfile(dig_path) or not os.access(dig_path, os.X_OK):
  214. print "It seems you don't have 'dig' command installed properly "\
  215. "on your system."
  216. sys.exit(2)
  217. global hosts
  218. try:
  219. with open(config['infile'], 'r') as infile:
  220. hosts = infile.readlines()
  221. except IOError as e:
  222. print e
  223. sys.exit(e.errno)
  224. if os.path.exists(config['outfile']):
  225. config['outfile'] += '.new'
  226. try:
  227. outfile = open(config['outfile'], 'w')
  228. except IOError as e:
  229. print e
  230. sys.exit(e.errno)
  231. print "Input: %s Output: %s\n" % (config['infile'], config['outfile'])
  232. threads = []
  233. t = watcher_thread()
  234. t.start()
  235. threads.append(t)
  236. worker_num = config['threadnum']
  237. lines_num = len(hosts)
  238. lines_per_thread = lines_num / worker_num
  239. lines_remain = lines_num % worker_num
  240. start_pt = 0
  241. for _ in range(worker_num):
  242. if not running: break
  243. lines_for_thread = lines_per_thread
  244. if lines_for_thread == 0 and lines_remain == 0:
  245. break
  246. if lines_remain > 0:
  247. lines_for_thread += 1
  248. lines_remain -= 1
  249. t = worker_thread(start_pt, start_pt + lines_for_thread)
  250. start_pt += lines_for_thread
  251. t.start()
  252. threads.append(t)
  253. for t in threads:
  254. t.join()
  255. try:
  256. outfile.writelines(hosts)
  257. except IOError as e:
  258. print e
  259. sys.exit(e.errno)
  260. sys.exit(0)
  261. if __name__ == '__main__':
  262. main()