Python switch Hosts file code example _python

Source: Internet
Author: User
Tags glob

Win7 The above requires the use of administrator privileges.

Copy Code code 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")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.