changehost 發表於 2016-06-04 | 分類於 python 最近写了一个自动修改host文件的代码: 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#encoding=utf-8import osimport reimport timeimport platformhost_window = r"C:\Windows\System32\drivers\etc\hosts"host_mac = r"/etc/hosts"B2B_UAT_HOST = ["#B2B uat deepblue2",'10.128.34.183 uat.englishtown.com','10.128.34.183 uat-cache.englishtown.com','10.128.34.233 uatdeepblue2.englishtown.com','10.128.34.233 uatdeepblue2cn.englishtown.com']HOST_LIVE = ["#LIVE","104.20.43.137 englishlive.ef.com","104.20.43.137 www.englishtown.com","104.20.43.137 www.englishtown.com.br","104.20.43.137 services.englishtown.com","104.20.43.137 etvt.englishtown.com","104.20.43.137 axis.englishtown.com","104.20.43.137 secure.englishtown.com","104.20.43.137 accenture.englishtown.com","104.20.43.137 accounts.ef.com"]def search_host(hostvalue,host_path): hostfile = open(host_path,'r') each_line = hostfile.readlines() hostfile.close() findresult = re.findall(hostvalue,''.join(each_line)) return findresultdef write_host(hostvalue,host_path): output = open(host_path, 'a') for insid in hostvalue: print insid output.write(insid) output.write("\n") output.close() if __name__ == "__main__": #inside_test() if platform.system is "Windows": host_path = host_window else: host_path = host_mac os.popen("sudo chmod 777 %s" %host_path) print host_path if search_host(HOST_LIVE[0],host_path): print ("Already exist") pass else: write_host(HOST_LIVE,host_path)