github_speed.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import requests
  2. host_path = "C:\Windows\System32\drivers\etc\hosts"
  3. # 读取hosts到 hostStr变量
  4. allHostStr = open(host_path, 'r', encoding='utf-8').read()
  5. print(allHostStr)
  6. print("*" * 100)
  7. # 请求最新的hosts
  8. headers = {
  9. 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
  10. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
  11. 'cache-control': 'no-cache',
  12. 'pragma': 'no-cache',
  13. 'sec-ch-ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
  14. 'sec-ch-ua-mobile': '?0',
  15. 'sec-ch-ua-platform': '"Windows"',
  16. 'sec-fetch-dest': 'document',
  17. 'sec-fetch-mode': 'navigate',
  18. 'sec-fetch-site': 'none',
  19. 'sec-fetch-user': '?1',
  20. 'upgrade-insecure-requests': '1',
  21. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
  22. }
  23. response = requests.get('https://gitlab.com/ineo6/hosts/-/raw/master/next-hosts', headers=headers)
  24. speedHostStr = response.text
  25. print(speedHostStr)
  26. start = "github start"
  27. end = "github end"
  28. speedHostStr = start + "\n" + speedHostStr + "\n" + end + "\n"
  29. # 如果已经存在,则替换
  30. if allHostStr.find(start) != -1:
  31. allHostStr = allHostStr[0:allHostStr.find("%s" % start)] + speedHostStr + allHostStr[allHostStr.find("%s" % end) + len("%s" % end):]
  32. else:
  33. allHostStr += speedHostStr
  34. print("*" * 100)
  35. print(allHostStr)
  36. # 写入hosts
  37. open(host_path, 'w', encoding='utf-8').write(allHostStr)