天朝上网需要经常改hosts文件的,你们都懂的。要在网上找啊,找到了还要复制粘贴,那叫一个麻烦啊。
我是出了名的懒人嘛,写个脚本干这事吧……
#!/usr/bin/env python
import urllib
import os
import platform
import shutil
#获取网页内容,网址是假的,我只是想说一下方法
r = urllib.urlopen(\'http://www.baidu.com/hosts.html\')
for line in r:
if line.find(\'NEW HOSTS\') >= 0:
url = line[line.find(\'http://\'):][:line[line.find(\'http://\'):].find(\'\"\')]
#设置hosts文件路径
if platform.system() == \'Windows\':
sysdir = os.getenv(\'SystemDrive\')
hostspath = sysdir + \'/windows/system32/drivers/etc/hosts\'
if platform.system() == \'Linux\':
hostspath = \'/etc/hosts\'
#备份hosts文件
if os.path.isfile(hostspath+\'_bak\') == False:
shutil.copyfile(hostspath,hostspath+\'_bak\')
shutil.copyfile(hostspath+\'_bak\',hostspath)
#读取文件,准备添加
host = open(hostspath,\'r\')
content = host.read()
host.close()
r = urllib.urlopen(url)
#开始添加
for line in r:
line=line.strip(\'\\n\')
content = content + line
#写入并关闭文件
host = open(hostspath,\'w\')
host.write(content)
host.close()