python check hosts update

来源:互联网 发布:stc单片机最小系统 编辑:程序博客网 时间:2024/05/22 15:59

用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 urllib2from .hosts_info import *import osimport filecmpdef 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