import requests host_path = "C:\Windows\System32\drivers\etc\hosts" # 读取hosts到 hostStr变量 allHostStr = open(host_path, 'r', encoding='utf-8').read() print(allHostStr) print("*" * 100) # 请求最新的hosts headers = { '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', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8', 'cache-control': 'no-cache', 'pragma': 'no-cache', 'sec-ch-ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"Windows"', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none', 'sec-fetch-user': '?1', 'upgrade-insecure-requests': '1', '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', } response = requests.get('https://gitlab.com/ineo6/hosts/-/raw/master/next-hosts', headers=headers) speedHostStr = response.text print(speedHostStr) start = "#github start" end = "#github end" speedHostStr = start + "\n" + speedHostStr + "\n" + end + "\n" # 如果已经存在,则替换 if allHostStr.find(start) != -1: allHostStr = allHostStr[0:allHostStr.find("%s" % start)] + speedHostStr + allHostStr[allHostStr.find("%s" % end) + len("%s" % end):] else: allHostStr += speedHostStr print("*" * 100) print(allHostStr) # 写入hosts open(host_path, 'w', encoding='utf-8').write(allHostStr) print("*" * 100) print("写入完成")