python切换hosts文件代码示例

yipeiwu_com5年前Python基础

win7以上需要使用管理员权限操作。

复制代码 代码如下:

# -*- 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")

相关文章

用python写asp详细讲解

用python写asp详细讲解

一、ASP的平反想到ASP 很多人会说 “asp语言很蛋疼,不能面向对象,功能单一,很多东西实现不了” 等等诸如此类。 以上说法都是错误的,其一ASp不是一种语言是 微软用来代替CGI的...

py2exe 编译ico图标的代码

复制代码 代码如下: #setup.py from distutils.core import setup import py2exe setup( # targets to build...

Python flask框架post接口调用示例

本文实例讲述了Python flask框架post接口调用。分享给大家供大家参考,具体如下: from flask import Flask,render_template,requ...

python使用锁访问共享变量实例解析

本文研究的主要是python使用锁访问共享变量,具体介绍和实现如下。 python 做多线程编程时,多个线程若同时访问某个变量,可能会对变量数据造成破坏,pyhon中的threading...

python中numpy.zeros(np.zeros)的使用方法

翻译: 用法:zeros(shape, dtype=float, order='C') 返回:返回来一个给定形状和类型的用0填充的数组; 参数:shape:形状 dtype:数据类型,可...