用Python检查 hosts 更新

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

hosts地址

hosts_info.py

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

检查hosts是否有更新

check_hosts.py

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

from check_hosts.check_hosts import *

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