When developing or testing website programs, we often encounter switching back and forth between multiple hosts files. The windows hosts file directory is very deep and troublesome. therefore, you have written a script in python to simplify this function. you need to use the administrator privilege for operations above win7.
The code is as follows:
#-*-Coding: UTF-8 -*-
Import OS
Import glob
Import shutil
Def format_file_list (files ):
All_files_str = ""
For I in range (len (files )):
All_files_str + = str (I) + ":" + files [I] + "\ n"
Return all_files_str
Hosts_path = "C :\\ Windows \ System32 \ drivers \ etc"
Files = OS. listdir (hosts_path)
OS. chdir (hosts_path)
If OS. getcwd ()! = Hosts_path:
Print ("Switch Dir to System32 Error, check permission! \ Npwd: "+ OS. getcwd ())
Exit ()
Hosts_files = glob. glob ("host *")
Choosed_file_idx = int (input ("Choose Hosts File Index: \ n" + format_file_list (hosts_files )))
Files_num = len (hosts_files)
If (choosed_file_idx <0 or choosed_file_idx> = files_num ):
Print ("Please choose a file in the lists! ")
Exit ()
Print ("Choosed idx: {0}, file: {1}.". format (choosed_file_idx, hosts_files [choosed_file_idx])
Shutil. copy ("hosts", "hosts. bak ")
Shutil. copy (hosts_files [choosed_file_idx], "hosts ")
Print ("Copy OK, then flush dns ...")
OS. system ("ipconfig/flushdns ")