首页 > 代码库 > Python脚本,自动更新host,添加or更新本机hosts

Python脚本,自动更新host,添加or更新本机hosts

#!/usr/bin/env python# -*- coding: utf-8 -*- import urllib2,re,platform#urlib2抓取网页def getContent(url, timeout=5):    content = None    try:        res = urllib2.urlopen(url, timeout=timeout)        content = res.read()    except urllib2.URLError, e:        print e.reason    return content#字符串查找关键词之前内容def getMain(content, keychars=#google hosts):    pos1 = content.find(keychars)    pos2 = content.find(keychars,pos1+len(keychars))    m = content[pos1:pos2+len(keychars)]    m = m.replace(&nbsp;, )    r = re.compile(r<[\w\s\/]+>)    return r.sub("", m)#source host urlurl = http://www.360kb.com/kb/2_122.html#标示字符串keychars = #google hosts#获取当前操作系统,判断修改文件路径syst = platform.system()if syst==Windows:    #windows    hosts = C:\\Windows\\System32\\drivers\\etc\\hostselse:    #linux    hosts = /etc/hostscontent = getContent(url, 5)if content==None:    exithostcontents = getMain(content,keychars)fp = open(hosts, rb)c = fp.read()fp.close()pos1 = c.find(keychars)if pos1==-1:    result = c+"\n"*2+hostcontentselse :    result = c[:pos1]+"\n"*2+hostcontentsfp = open(hosts, wb)fp.write(result)fp.close()

 

Python脚本,自动更新host,添加or更新本机hosts