github.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. '''
  4. @Contact : liuyuqi.gov@msn.cn
  5. @Time : 2019/08/03 16:16:59
  6. @License : Copyright © 2017-2022 liuyuqi. All Rights Reserved.
  7. @Desc : refeash github host everyday
  8. '''
  9. import os
  10. import datetime
  11. from github_host import get_ip_utils
  12. from github_host.libs.json_conf import JsonConf
  13. class Github(object):
  14. def __init__(self):
  15. self.jsonConf = JsonConf()
  16. self.conf = self.jsonConf.load()
  17. self.sites = self.conf.get('sites')
  18. self.addr2ip = {}
  19. self.hostLocation = r"hosts"
  20. def dropDuplication(self, line):
  21. flag = False
  22. if "#*******" in line:
  23. return True
  24. for site in self.sites:
  25. if site in line:
  26. flag = flag or True
  27. else:
  28. flag = flag or False
  29. return flag
  30. def saveRouterosFile(self):
  31. ''' 应网友需求,导出一份 routeros 格式的hosts文件 '''
  32. today = datetime.date.today()
  33. with open("hosts-routeros.txt", "w") as f:
  34. f.write("#*********************github " +
  35. str(today) + " update********************\n")
  36. f.write(
  37. "#******* get latest hosts: http://blog.yoqi.me/lyq/16489.html\n")
  38. for key in self.addr2ip:
  39. f.write("add address=" + self.addr2ip[key] + " name="+ key + "\n")
  40. # 更新host, 并刷新本地DNS
  41. def updateHost(self):
  42. today = datetime.date.today()
  43. for site in self.sites:
  44. trueip = get_ip_utils.getIpFromipapi(site)
  45. if trueip != None:
  46. self.addr2ip[site] = trueip
  47. print(site + "\t" + trueip)
  48. with open(self.hostLocation, "r") as f1:
  49. f1_lines = f1.readlines()
  50. with open("temphost", "w") as f2:
  51. for line in f1_lines: # 为了防止 host 越写用越长,需要删除之前更新的含有github相关内容
  52. if self.dropDuplication(line) == False:
  53. f2.write(line)
  54. f2.write("#*********************github " +
  55. str(today) + " update********************\n")
  56. f2.write(
  57. "#******* get latest hosts: http://blog.yoqi.me/lyq/16489.html\n")
  58. for key in self.addr2ip:
  59. f2.write(self.addr2ip[key] + "\t" + key + "\n")
  60. os.remove(self.hostLocation)
  61. os.rename("temphost", self.hostLocation)
  62. # os.system("ipconfig /flushdns")
  63. self.saveRouterosFile()