使用python、windows定时任务自动更新github的hosts
安装python环境
引入requests模块
pip install requests
新建python(.py)文件
写入以下内容
import requests # 导入request模块
url = "https://raw.hellogithub.com/hosts" # 指定url
r = requests.get(url) # 基于request模块给url网站发送请求
print(r.content) # 以字节形式返回响应体
file = open('C:\Windows\System32\drivers\etc\hosts', mode='w') # 打开hosts文件
file.seek(0) # 移动文件指针至文档开头
file.truncate() # 清空文档
file.write(r.content.decode('UTF-8')) # 写入 decode('UTF-8')将字节形式转为字符串
新建批处理(.bat)文件
写入以下内容
py python.py # 上面新建的python文件
windows创建定时任务
将上面的python文件和批处理文件放在同一目录下,创建定时任务执行批处理文件
注意下图中的‘起始于’这一项