首页 > 代码库 > 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(‘ ‘,‘ ‘) 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\\hosts‘else: #linux hosts = ‘/etc/hosts‘content = 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。