github.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. # 更新host, 并刷新本地DNS
  31. def updateHost(self):
  32. today = datetime.date.today()
  33. for site in self.sites:
  34. trueip = get_ip_utils.getIpFromipapi(site)
  35. if trueip != None:
  36. self.addr2ip[site] = trueip
  37. print(site + "\t" + trueip)
  38. with open(self.hostLocation, "r") as f1:
  39. f1_lines = f1.readlines()
  40. with open("temphost", "w") as f2:
  41. for line in f1_lines: # 为了防止 host 越写用越长,需要删除之前更新的含有github相关内容
  42. if self.dropDuplication(line) == False:
  43. f2.write(line)
  44. f2.write("#*********************github " +
  45. str(today) + " update********************\n")
  46. f2.write(
  47. "#******* get latest hosts: http://blog.yoqi.me/lyq/16489.html\n")
  48. for key in self.addr2ip:
  49. f2.write(self.addr2ip[key] + "\t" + key + "\n")
  50. os.remove(self.hostLocation)
  51. os.rename("temphost", self.hostLocation)