例子,用python更新linux下hosts文件。
复制代码 代码示例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#author:mrsimple
import sys
import urllib
import os
from shutil import copyfile
HOSTS_URL='https://smarthosts.googlecode.com/svn/trunk/hosts'
LOCAL_HOSTS='/etc/hosts'
def update():
"""update hosts from smarthost"""
# backup hosts file
copyfile(LOCAL_HOSTS,'hosts.bak')
with open(LOCAL_HOSTS,'aw') as hosts:
# 字符串给出当前平台使用的行终止符。例如,Windows使用'rn',Linux使用'n'而Mac使用'r'。
hosts.write(os.linesep)
for line in urllib.urlopen(HOSTS_URL):
hosts.write(line.strip()+os.linesep)
print "success!"
if __name__ == '__main__':
if len(sys.argv)>1:
HOSTS_URL = sys.argv[1]
update()