编辑
2024-05-06
学习
00
请注意,本文编写于 168 天前,最后修改于 168 天前,其中某些信息可能已经过时。

目录

代码
定时运行

实现该功能需要依赖 https://github.com/ineo6/hosts 项目

image.png

代码

python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests # 定义源URL和目标文件 source_url = "https://gitlab.com/ineo6/hosts/-/raw/master/hosts" target_file = "/etc/hosts" # 定义标记 start_marker = "# >>>>start\n" end_marker = "\n# <<<<end" def fetch_latest_content(url): # 发送GET请求获取最新内容 response = requests.get(url) if response.status_code == 200: return response.text.splitlines() else: print(f"无法从 {url} 获取内容。") return None def update_host_file_with_new_content(source_content, file_path): # 构建新的内容 new_content = start_marker + '\n' + '\n'.join(source_content) + end_marker + '\n' # 替换目标文件中的内容 try: with open(file_path, 'r+') as f: file_data = f.read() start_pos = file_data.find(start_marker) end_pos = file_data.find(end_marker, start_pos + len(start_marker)) if start_pos != -1 and end_pos != -1: f.seek(0) f.truncate() f.write(file_data[:start_pos]) f.write(new_content) f.write(file_data[end_pos + len(end_marker):]) print("目标文件已更新。") else: print("未找到标记,无法替换内容。") except FileNotFoundError: print(f"文件 {file_path} 未找到。") except IOError: print(f"无法写入到文件 {file_path}。") def main(): # 获取最新内容 latest_content = fetch_latest_content(source_url) if latest_content: # 更新目标文件中的内容 update_host_file_with_new_content(latest_content, target_file) else: print("未能获取最新内容。") if __name__ == "__main__": main()

上面的脚本会获取到 https://gitlab.com/ineo6/hosts/-/raw/master/hosts 的内容,然后插入到/etc/hosts 文件的 start_marker 和 end_marker 之间

请手动在 /etc/hosts 中添加 start_marker 和 end_marker

定时运行

在 crontab 中添加定时任务

  1. 打开 crontab 文件
bash
sudo vim /etc/crontab
  1. 添加定时任务

这是我的脚本路径,请自行替换为自己的路径

bash
30 * * * * root /usr/bin/python3 /home/beiklive/Host/updateHost.py >> /home/beiklive/Host/log.log 2>&1
  1. 刷新crontab
bash
sudo systemctl restart cron

本文作者:beiklive

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!