python自动更新hosts

windows 自动获得 google hosts 并更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import requests

# windows系统 hosts文件地址
hosts_file_dir = 'C:/Windows/System32/drivers/etc/hosts'
# 自定义 hosts
local_hosts = '127.0.0.1 localhost\n\n\n'

# google hosts url
goog_hosts_url = 'https://coding.net/u/scaffrey/p/hosts/git/raw/master/hosts-files/hosts'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3689.0 Safari/537.36'}
req = requests.get(goog_hosts_url, headers=headers)
goog_hosts = req.content.decode(encoding='utf-8')

print('- hosts downloaded !!!\n')


with open(hosts_file_dir, 'wb') as fd:
fd.write(bytes(local_hosts + goog_hosts, 'UTF-8'))

print('- hosts update succeed !')