Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

186 wiersze
6.0 KiB

3 lat temu
3 lat temu
2 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
3 lat temu
  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. import requests
  15. from retry import retry
  16. RAW_URL = [
  17. "alive.github.com",
  18. "live.github.com",
  19. "github.githubassets.com",
  20. "central.github.com",
  21. "desktop.githubusercontent.com",
  22. "assets-cdn.github.com",
  23. "camo.githubusercontent.com",
  24. "github.map.fastly.net",
  25. "github.global.ssl.fastly.net",
  26. "gist.github.com",
  27. "github.io",
  28. "github.com",
  29. "github.blog",
  30. "api.github.com",
  31. "raw.githubusercontent.com",
  32. "user-images.githubusercontent.com",
  33. "favicons.githubusercontent.com",
  34. "avatars5.githubusercontent.com",
  35. "avatars4.githubusercontent.com",
  36. "avatars3.githubusercontent.com",
  37. "avatars2.githubusercontent.com",
  38. "avatars1.githubusercontent.com",
  39. "avatars0.githubusercontent.com",
  40. "avatars.githubusercontent.com",
  41. "codeload.github.com",
  42. "github-cloud.s3.amazonaws.com",
  43. "github-com.s3.amazonaws.com",
  44. "github-production-release-asset-2e65be.s3.amazonaws.com",
  45. "github-production-user-asset-6210df.s3.amazonaws.com",
  46. "github-production-repository-file-5c1aeb.s3.amazonaws.com",
  47. "githubstatus.com",
  48. "github.community",
  49. "github.dev",
  50. "media.githubusercontent.com",
  51. "cloud.githubusercontent.com",
  52. "objects.githubusercontent.com"]
  53. IPADDRESS_PREFIX = ".ipaddress.com"
  54. HOSTS_TEMPLATE = """# GitHub520 Host Start
  55. {content}
  56. # Update time: {update_time}
  57. # Update url: https://raw.hellogithub.com/hosts
  58. # Star me: https://github.com/521xueweihan/GitHub520
  59. # GitHub520 Host End\n"""
  60. def write_file(hosts_content: str, update_time: str):
  61. output_doc_file_path = os.path.join(os.path.dirname(__file__), "README.md")
  62. template_path = os.path.join(os.path.dirname(__file__),
  63. "README_template.md")
  64. write_host_file(hosts_content)
  65. if os.path.exists(output_doc_file_path):
  66. with open(output_doc_file_path, "r") as old_readme_fb:
  67. old_content = old_readme_fb.read()
  68. old_hosts = old_content.split("```bash")[1].split("```")[0].strip()
  69. old_hosts = old_hosts.split("# Update time:")[0].strip()
  70. hosts_content_hosts = hosts_content.split("# Update time:")[0].strip()
  71. if old_hosts == hosts_content_hosts:
  72. print("host not change")
  73. return False
  74. with open(template_path, "r") as temp_fb:
  75. template_str = temp_fb.read()
  76. hosts_content = template_str.format(hosts_str=hosts_content,
  77. update_time=update_time)
  78. with open(output_doc_file_path, "w") as output_fb:
  79. output_fb.write(hosts_content)
  80. return True
  81. def write_host_file(hosts_content: str):
  82. output_file_path = os.path.join(os.path.dirname(__file__), 'hosts')
  83. with open(output_file_path, "w") as output_fb:
  84. output_fb.write(hosts_content)
  85. def write_json_file(hosts_list: list):
  86. output_file_path = os.path.join(os.path.dirname(__file__), 'hosts.json')
  87. with open(output_file_path, "w") as output_fb:
  88. json.dump(hosts_list, output_fb)
  89. def make_ipaddress_url(raw_url: str):
  90. """
  91. ipaddress url
  92. :param raw_url: url
  93. :return: ipaddress url
  94. """
  95. dot_count = raw_url.count(".")
  96. if dot_count > 1:
  97. raw_url_list = raw_url.split(".")
  98. tmp_url = raw_url_list[-2] + "." + raw_url_list[-1]
  99. ipaddress_url = "https://" + tmp_url + IPADDRESS_PREFIX + "/" + raw_url
  100. else:
  101. ipaddress_url = "https://" + raw_url + IPADDRESS_PREFIX
  102. return ipaddress_url
  103. @retry(tries=3)
  104. def get_ip(session: requests.session, raw_url: str):
  105. url = make_ipaddress_url(raw_url)
  106. try:
  107. rs = session.get(url, timeout=5)
  108. pattern = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"
  109. ip_list = re.findall(pattern, rs.text)
  110. ip_counter_obj = Counter(ip_list).most_common(1)
  111. if ip_counter_obj:
  112. return raw_url, ip_counter_obj[0][0]
  113. raise Exception("ip address empty")
  114. except Exception as ex:
  115. print("get: {}, error: {}".format(url, ex))
  116. raise Exception
  117. @retry(tries=3)
  118. def update_gitee_gist(session: requests.session, host_content):
  119. gitee_token = os.getenv("gitee_token")
  120. gitee_gist_id = os.getenv("gitee_gist_id")
  121. gist_file_name = os.getenv("gitee_gist_file_name")
  122. url = "https://gitee.com/api/v5/gists/{}".format(gitee_gist_id)
  123. headers = {
  124. "Content-Type": "application/json"}
  125. data = {
  126. "access_token": gitee_token,
  127. "files": {gist_file_name: {"content": host_content}},
  128. "public": "true"}
  129. json_data = json.dumps(data)
  130. try:
  131. response = session.patch(url, data=json_data, headers=headers,
  132. timeout=20)
  133. if response.status_code == 200:
  134. print("update gitee gist success")
  135. else:
  136. print("update gitee gist fail: {} {}".format(response.status_code,
  137. response.content))
  138. except Exception as e:
  139. traceback.print_exc(e)
  140. raise Exception(e)
  141. def main():
  142. session = requests.session()
  143. content = ""
  144. content_list = []
  145. for raw_url in RAW_URL:
  146. try:
  147. host_name, ip = get_ip(session, raw_url)
  148. content += ip.ljust(30) + host_name + "\n"
  149. content_list.append((ip, host_name,))
  150. except Exception:
  151. continue
  152. if not content:
  153. return
  154. update_time = datetime.utcnow().astimezone(
  155. timezone(timedelta(hours=8))).replace(microsecond=0).isoformat()
  156. hosts_content = HOSTS_TEMPLATE.format(content=content, update_time=update_time)
  157. has_change = write_file(hosts_content, update_time)
  158. if has_change:
  159. write_json_file(content_list)
  160. print(hosts_content)
  161. if __name__ == '__main__':
  162. main()