歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> Google Hosts更新腳本

Google Hosts更新腳本

日期:2017/3/2 10:04:22   编辑:關於Linux

# -*- coding: utf-8 -*-

__author__ = 'xu.zhibin'
__createDateTime__ = '2012-06-25 11:54'

import os
import sys
import re
import urllib2

updateUrl="https://smarthosts.googlecode.com/svn/trunk/hosts"
hostPath="C:\WINDOWS\system32\drivers\etc\hosts"
pattern=re.compile(r"#Google Services START([\s|\S]*)#Google Services END")

#獲取最新的Google Hosts
try:
updateHost=urllib2.urlopen(updateUrl)
updateContent=updateHost.read()
except Exception,ex:
print "獲取最新的Google Hosts失敗!"
raw_input()
sys.exit()
match = pattern.search(updateContent)
if match != None:
googleContent=updateContent[match.start():match.end()]

#本地Hosts
hostFile=open(hostPath,'r+')
hostContent=hostFile.read()
bakContent = pattern.sub('',hostContent)
bakContent = re.sub("\n\n","\n",bakContent)
hostContent = googleContent+"\n"+bakContent
hostFile.seek(0)
hostFile.write(hostContent)
hostFile.close()

#Hosts 備份
bakPath="%s_bak" % hostPath
bakFile=open(bakPath,'w')
bakFile.write(bakContent)
bakFile.close()

print "更新Hosts成功!"
raw_input()

Copyright © Linux教程網 All Rights Reserved