码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-12-31 12:54:18      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

#!/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 url
url = ‘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:
    exit
hostcontents = getMain(content,keychars)

fp = open(hosts, ‘rb‘)
c = fp.read()
fp.close()

pos1 = c.find(keychars)
if pos1==-1:
    result = c+"\n"*2+hostcontents
else :
    result = c[:pos1]+"\n"*2+hostcontents

fp = open(hosts, ‘wb‘)
fp.write(result)
fp.close()

 

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

标签:

原文地址:http://www.cnblogs.com/spacex/p/4195331.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!