天天看點

工作筆記--Python自動切換host

修改host代碼:

#coding:utf-8
import os,time

pwd = os.path.dirname(__file__) #擷取目前檔案夾的絕對路徑
pull_host_cmd = 'adb pull system/etc/hosts '+pwd
push_host_cmd = 'adb push '+pwd+'\hosts system/etc/'

os.popen('adb root')
temp = os.popen('adb remount')

print 'Pull hosts..'
temp = os.popen(pull_host_cmd)
temp = temp.readline().split()

#讀取配置檔案       
config_path = os.path.join(pwd, 'config.txt') #擷取目前檔案夾内的config檔案
config_file = open(config_path, "r") #讀取檔案

#寫追加方式打開host檔案
host_path = os.path.join(pwd,'hosts')
host_file = open(host_path,"a+")

for line in config_file:
   host_file.write(line)
   
config_file.close() #關閉檔案
host_file.close()

#push hosts
temp = os.popen(push_host_cmd)
temp = temp.readline().split()
temp = os.system('del hosts')

重置到localhost的代碼:      
#coding:utf-8
import os,time

pwd = os.path.dirname(__file__) #擷取目前檔案夾的絕對路徑
pull_host_cmd = 'adb pull system/etc/hosts '+pwd
push_host_cmd = 'adb push '+pwd+'\hosts system/etc/'

temp = os.popen(pull_host_cmd)
temp = temp.readline().split()

host_path = os.path.join(pwd,'hosts')
host_file = open(host_path,"wb")

host_file.write('127.0.0.1 localhost\n')
host_file.close()
os.system('adb push hosts system/etc/hosts')
os.system('del hosts')

Project目錄:      
工作筆記--Python自動切換host