Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

164 linhas
5.3 KiB

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. #
  4. # Author : XueWeiHan
  5. # E-mail : 595666367@qq.com
  6. # Date : 2020-05-19 15:27
  7. # Desc : 获取最新的 GitHub 相关域名对应 IP
  8. import os
  9. import re
  10. import json
  11. import traceback
  12. from datetime import datetime, timezone, timedelta
  13. from collections import Counter
  14. from retry import retry
  15. import requests
  16. RAW_URL = [
  17. "github.githubassets.com",
  18. "camo.githubusercontent.com",
  19. "github.map.fastly.net",
  20. "github.global.ssl.fastly.net",
  21. "gist.github.com",
  22. "github.io",
  23. "github.com",
  24. "api.github.com",
  25. "raw.githubusercontent.com",
  26. "user-images.githubusercontent.com",
  27. "favicons.githubusercontent.com",
  28. "avatars5.githubusercontent.com",
  29. "avatars4.githubusercontent.com",
  30. "avatars3.githubusercontent.com",
  31. "avatars2.githubusercontent.com",
  32. "avatars1.githubusercontent.com",
  33. "avatars0.githubusercontent.com",
  34. "codeload.github.com",
  35. "github-cloud.s3.amazonaws.com",
  36. "github-com.s3.amazonaws.com",
  37. "github-production-release-asset-2e65be.s3.amazonaws.com",
  38. "github-production-user-asset-6210df.s3.amazonaws.com",
  39. "github-production-repository-file-5c1aeb.s3.amazonaws.com"]
  40. IPADDRESS_PREFIX = ".ipaddress.com"
  41. HOSTS_TEMPLATE = """# GitHub520 Host Start
  42. {content}# Star me GitHub url: https://github.com/521xueweihan/GitHub520
  43. # GitHub520 Host End\n"""
  44. def write_file(hosts_content: str):
  45. update_time = datetime.utcnow().astimezone(
  46. timezone(timedelta(hours=8))).replace(microsecond=0).isoformat()
  47. output_doc_file_path = os.path.join(os.path.dirname(__file__), "README.md")
  48. template_path = os.path.join(os.path.dirname(__file__),
  49. "README_template.md")
  50. # 应该取消 write yaml file,改成 gitee gist 地址同步(国内访问流畅)
  51. write_yaml_file(hosts_content)
  52. with open(output_doc_file_path, "r") as old_readme_fb:
  53. old_content = old_readme_fb.read()
  54. old_hosts = old_content.split("```bash")[1].split("```")[0].strip()
  55. if old_hosts == hosts_content:
  56. print("host not change")
  57. return False
  58. with open(template_path, "r") as temp_fb:
  59. template_str = temp_fb.read()
  60. hosts_content = template_str.format(hosts_str=hosts_content,
  61. update_time=update_time)
  62. with open(output_doc_file_path, "w") as output_fb:
  63. output_fb.write(hosts_content)
  64. return True
  65. def write_yaml_file(hosts_content: str):
  66. output_yaml_file_path = os.path.join(os.path.dirname(__file__), 'hosts')
  67. with open(output_yaml_file_path, "w") as output_yaml_fb:
  68. output_yaml_fb.write(hosts_content)
  69. def make_ipaddress_url(raw_url: str):
  70. """
  71. ipaddress url
  72. :param raw_url: url
  73. :return: ipaddress url
  74. """
  75. dot_count = raw_url.count(".")
  76. if dot_count > 1:
  77. raw_url_list = raw_url.split(".")
  78. tmp_url = raw_url_list[-2] + "." + raw_url_list[-1]
  79. ipaddress_url = "https://" + tmp_url + IPADDRESS_PREFIX + "/" + raw_url
  80. else:
  81. ipaddress_url = "https://" + raw_url + IPADDRESS_PREFIX
  82. return ipaddress_url
  83. @retry(tries=3)
  84. def get_ip(session: requests.session, raw_url: str):
  85. url = make_ipaddress_url(raw_url)
  86. try:
  87. rs = session.get(url, timeout=5)
  88. pattern = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"
  89. ip_list = re.findall(pattern, rs.text)
  90. ip_counter_obj = Counter(ip_list).most_common(1)
  91. if ip_counter_obj:
  92. return raw_url, ip_counter_obj[0][0]
  93. raise Exception("ip address empty")
  94. except Exception as ex:
  95. print("get: {}, error: {}".format(url, ex))
  96. raise Exception
  97. @retry(tries=3)
  98. def update_gitee_gist(session: requests.session, host_content):
  99. gitee_token = os.getenv("gitee_token")
  100. gitee_gist_id = os.getenv("gitee_gist_id")
  101. gist_file_name = os.getenv("gitee_gist_file_name")
  102. url = "https://gitee.com/api/v5/gists/{}".format(gitee_gist_id)
  103. headers = {
  104. "Content-Type": "application/json"}
  105. data = {
  106. "access_token": gitee_token,
  107. "files": {gist_file_name: {"content": host_content}},
  108. "public": "true"}
  109. json_data = json.dumps(data)
  110. try:
  111. response = session.patch(url, data=json_data, headers=headers,
  112. timeout=20)
  113. if response.status_code == 200:
  114. print("update gitee gist success")
  115. else:
  116. print("update gitee gist fail: {} {}".format(response.status_code,
  117. response.content))
  118. except Exception as e:
  119. traceback.print_exc(e)
  120. raise Exception(e)
  121. def main():
  122. session = requests.session()
  123. content = ""
  124. for raw_url in RAW_URL:
  125. try:
  126. host_name, ip = get_ip(session, raw_url)
  127. content += ip.ljust(30) + host_name + "\n"
  128. except Exception:
  129. continue
  130. if not content:
  131. return
  132. hosts_content = HOSTS_TEMPLATE.format(content=content)
  133. has_change = write_file(hosts_content)
  134. if has_change:
  135. try:
  136. update_gitee_gist(session, hosts_content)
  137. except Exception as e:
  138. print("update gitee gist fail:{}".format(e))
  139. print(hosts_content)
  140. if __name__ == '__main__':
  141. main()