用Python检查 hosts 更新

最近各种代理纷纷关闭,常见的翻墙方式就剩lantern和更改hosts的方式依旧坚挺,关注了一些更新hosts的git仓库,但是又不想登录网页查看原作者是否有更新。所以这种苦力活就让Python干好了。

hosts地址

hosts_info.py

1
hosts_source = ["https://raw.githubusercontent.com/racaljk/hosts/master/hosts"]

检查hosts是否有更新

check_hosts.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import urllib2
from .hosts_info import *
import os
import filecmp


def hosts_download():
if os.path.exists('hosts'):
hosts_name = 'hosts_new'
else:
hosts_name = 'hosts'

# todo: overtime detection
f = urllib2.urlopen(hosts_source[0])
print "downloading hosts"
with open(hosts_name, "wb") as code:
code.write(f.read())

def is_hosts_new():

hosts_download()

if not os.path.exists('hosts'):
print 'oops, hosts not exists'
return -1

elif os.path.exists('hosts') and (not os.path.exists('hosts_new')):
print 'first run, only one hosts file'
return True

elif os.path.exists('hosts') and (os.path.exists('hosts_new')):
print 'compare hosts & hosts_new'
diff_status = filecmp.cmp('hosts', 'hosts_new')
if diff_status:
print 'same file'
os.remove('hosts_new')
return False
else:
print 'diff file'
os.remove('hosts')
os.rename('hosts_new', "hosts")
return True
else:
return -1

主程序调用

main.py

1
2
3
4
5
6
7
from check_hosts.check_hosts import *

diff_status = is_hosts_new()
if diff_status:
print "new hosts !"
else:
print 'code: ',diff_status